1

嗨,我最近正在开发一个代码,我必须提取最后 3 组数字。所以我使用模式来提取数据。但我没能理解。任何人都可以帮助我理解它吗?

    String str ="EGLA 0F 020";
    String def = "ALT 1F 001 TO ALT 1F 029";
    String arr[] = def.split("TO");
    String str2 = arr[0];
    System.out.println("str2:"+str2);
    Pattern pt = Pattern.compile("[0-9][0-9][0-9]$");
    Matcher m1 = pt.matcher(str);
    Matcher m2 = pt.matcher(str2);
    boolean flag = m1.find();
    boolean flag2 = m2.find();
    if(flag)
        System.out.println("first match:::"+m1.group(0));
    else 
        System.out.println("Not found");
    if(flag2)
        System.out.println("first match:::"+m2.group(0));
    else
        System.out.println("Not found");

上述代码产生的输出如下:::

    str2:ALT 1F 001 
    first match:::020
    Not found

请回复我卡在这里??

4

3 回答 3

2

这是因为当你拆分时,你有一个尾随空格。

String str = "EGLA 0F 020";
String str2 = "ALT 1F 001 ";
//                       ^ trailing space

您可以通过多种方式修复它。例如:

  • 通过拆分" TO "
  • 修剪结果
  • 在正则表达式中允许尾随空格。

例如,此更改将起作用:

String arr[] = def.split(" TO ");
于 2011-10-17T13:37:42.460 回答
0

如果您注意到您的拆分仅对字母生效"TO",则表示 str2 模式是"ALT 1F 001 ".

要解决此问题,您可以尝试拆分,"\s*TO\s*"而不是"TO"这样,工作 TO 周围的任何空格也将被删除。另一种解决方案是"[0-9][0-9][0-9]$""[0-9][0-9][0-9]"没有 final替换您的模式$,以便它接受您的字符串上的结尾空格。

于 2011-10-17T13:41:10.397 回答
0

试试这个模式:

Pattern pattern = Pattern.compile("[0-9][0-9][0-9]\\s*$"); 

或者

Pattern pattern = Pattern.compile("[0-9]{3}\\s*$"); 
于 2011-10-17T13:45:45.480 回答