繁体   English   中英

java正则表达式捕获2个数字

[英]java regex capturing 2 numbers

我正在寻找一种方法来捕获字符串的年份和最后一个数字。 例如:“01/02/2017,546.12,24.2”,到目前为止,我的问题只有 Found value : 2017 和 Found value : 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");
        }
    }
}

试试这个:

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

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

你的要求不是很清楚,但这对我来说只是简单地获取年份和最后一个十进制值:

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);
}

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

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

解析,而不是正则表达式

正则表达式在这里有点矫枉过正。

只需在逗号分隔符上拆分字符串即可。

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 );

查看此代码在 IdeOne.com 上实时运行

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

year.toString(): 2017

lastNumber.toString(): 24.2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM