请参阅以下代码
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()将变为false。
请建议用于两种类型字符串“abc_dfgb_tf”和“abc_dfgb_tf + 1cbv”的模式
帮助
答案 0 :(得分:5)
你似乎想要这样的东西:
String pattern1 = "(\\w+)(?:([+-])(\\d+)(\\w+))?";
这使得可选尾部实际上是可选的。
答案 1 :(得分:2)
您似乎想要除第一组以外的可选所有内容。像
这样的东西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