请参考下面的代码

    String line = "abc_dfgb_tf";

    String pattern1 = "(\\w+)([+-])(\\d+)(\\w+)";
    Pattern r1 = Pattern.compile(pattern1);
    Matcher m1 = r1.matcher(line);

    if (m1.find( ))
    {
       System.out.println("Found value: " + m1.group(1) );
       System.out.println("Found value: " + m1.group(2) );
       System.out.println("Found value: " + m1.group(3) );
       System.out.println("Found value: " + m1.group(4) );
    }


如果是“ abc_dfgb_tf”,则字符串m1.find()为假。

请建议用于字符串“ abc_dfgb_tf”和“ abc_dfgb_tf + 1cbv”两种类型的模式

救命

最佳答案

您似乎想要除第一组以外的所有内容都是可选的。就像是

String line = "abc_dfgb_tf";
String pattern1 = "(\\w+)([+-]*)(\\d*)(\\w*)";
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(line);

if (m1.find()) {
    System.out.println("Found value: " + m1.group(1));
    System.out.println("Found value: " + m1.group(2));
    System.out.println("Found value: " + m1.group(3));
    System.out.println("Found value: " + m1.group(4));
}


输出是

Found value: abc_dfgb_tf
Found value:
Found value:
Found value:


如果我将行更改为String line = "abc_dfgb_tf+1cbv";输出是

Found value: abc_dfgb_tf
Found value: +
Found value: 1
Found value: cbv

09-25 16:07
查看更多