【问题标题】:java regex capturing 2 numbersjava正则表达式捕获2个数字
【发布时间】:2017-10-05 19:32:23
【问题描述】:

我正在寻找一种方法来捕获年份和字符串的最后一个数字。例如:“01/02/2017,546.12,24.2”,到目前为止,我的问题只有 Found 值:2017 和 Found 值:null。我无法捕获组 (2)。谢谢

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;


public class Bourse {

    public static void main( String args[] ) {
        Scanner clavier = new Scanner(System.in);

        // String to be scanned to find the pattern.
        String line = clavier.nextLine();
        String pattern = "(?<=\\/)(\\d{4})|(\\d+(?:\\.\\d{1,2}))(?=,$)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);

        if (m.find( )) {
            System.out.println("Found value: " + m.group(1) );
            System.out.println("Found value: " + m.group(2) );
        } else {
            System.out.println("NO MATCH");
        }
    }
}

【问题讨论】:

  • 字符串输入 = "01/02/2017,654.45,20.78" 和预期输出 = 2017,这是您的问题吗?您想在这种模式中实现什么目标?
  • 你的问题有点不清楚。您发布了您想做的事情,但没有解释您在实施时遇到的问题。
  • 我想要输出 = 2017 和 20.78
  • 同样,这是代码要求,而不是您在创建代码时面临的问题的描述。我们希望有这样的描述,以便其他面临相同问题的人找到您的问题和可能的答案。
  • 我的问题是我只得到了 Found value: 2017 和 Found value: null

标签: java regex capture-group


【解决方案1】:

试试这个:

(\\d{2}\\.?\\d{2})
  • \\d{2} - 正好是两位数
  • \\.? - 可选点
  • \\d{2} - 正好是两位数

如果我理解正确,您正在寻找 4 位数字,可以用点分隔。

【讨论】:

  • 谢谢,但没有。我想得到年份和最后一个数字例如:01/02/2017,654.45,20.78,我想要 2017 和 20.78
【解决方案2】:

您的要求不是很清楚,但这对我来说只需获取年份和最后一个小数:

Pattern pattern = Pattern.compile("[0-9]{2}/[0-9]{2}/([0-9]{4}),[^,]+,([0-9.]+),");
String text = "01/02/2017,546.12,24.2,";
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    String year = matcher.group(1);
    String lastDecimal = matcher.group(2);
    System.out.println("Year "+year+"; decimal "+lastDecimal);
}

我不知道你是否故意使用lookbehind和lookahead,但我认为显式指定完整日期模式并使用两个显式逗号字符之间的值更简单。 (显然,如果您需要逗号继续播放,您可以用前瞻替换最后的逗号。)

顺便说一句,我不喜欢 \d 速记,因为在许多语言中,这将匹配整个 Unicode 字符空间中的所有数字字符,而通常只需要匹配 ASCII 数字 0-9。 (使用\d时Java确实只匹配ASCII数字,但我仍然认为这是一个坏习惯。)

【讨论】:

    【解决方案3】:

    解析,而不是正则表达式

    Regex 在这里太过分了。

    只需拆分逗号上的字符串-delimiter。

    String input = "01/02/2017,546.12,24.2,";
    String[] parts = input.split( "," );
    

    将每个元素解析为有意义的对象,而不是将所有内容都视为文本。

    对于仅日期值,现代方法使用 Java 8 及更高版本中内置的 java.time.LocalDate 类。

    // Parse the first element, a date-only value.
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
    LocalDate localDate = null;
    String inputDate =  parts[ 0 ] ;
    try
    {
       localDate =  LocalDate.parse( inputDate , f );
    } catch ( DateTimeException e )
    {
        System.out.println( "ERROR - invalid input for LocalDate: " + parts[ 0 ] );
    }
    

    对于精度很重要的小数数字,请避免使用浮点类型,而是使用BigDecimal。鉴于您的班级名称“Bourse”,我假设这些数字与金钱有关,因此准确性很重要。对于金钱问题,请始终使用BigDecimal。

    // Loop the numbers
    List < BigDecimal > numbers = new ArrayList <>( parts.length );
    for ( int i = 1 ; i < parts.length ; i++ )
    {  // Start index at 1, skipping over the first element (the date) at index 0.
        String s = parts[ i ];
        if ( null == s )
        {
            continue;
        }
        if ( s.isEmpty( ) )
        {
            continue;
        }
        BigDecimal bigDecimal = new BigDecimal( parts[ i ] );
        numbers.add( bigDecimal );
    }
    

    提取您想要的两条信息:年份和最后一个数字。

    考虑在您的代码中传递一个Year 对象,而不是仅仅通过一个整数来表示年份。这为您提供了类型安全性并使您的代码更具自我记录性。

    // Goals: (1) Get the year of the date. (2) Get the last number.
    Year year = Year.from( localDate );  // Where possible, use an object rather than a mere integer to represent the year.
    int y = localDate.getYear( );
    BigDecimal lastNumber = numbers.get( numbers.size( ) - 1 );  // Fetch last element from the List.
    

    转储到控制台。

    System.out.println("input: " + input );
    System.out.println("year.toString(): " + year );
    System.out.println("lastNumber.toString(): " + lastNumber );
    

    看到这个code run live at IdeOne.com。

    输入:01/02/2017,546.12,24.2,

    year.toString(): 2017

    lastNumber.toString(): 24.2

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2014-01-02
      相关资源
      最近更新 更多