String allString = " I1 + I6 + I9 + I8 + I3 + I2 + I20 + I21 + I18 + I23 + I28 + I27 + I31 + I24 + I12 + I15 + I14 + I13 + I16 + I11 "
我如何只检查" I1"在java正则表达式模式中。输入模式是" I1" ," I6" ....." I11"。在这种情况下" I1" ," I12" ," I15" ," I14" ," I13" ," I16" " I11"是相同的" I1"输入模式。怎么解决?
答案 0 :(得分:0)
您可以使用简单的正则表达式模式I1\d*
,即I1
后跟任意数量的数字。
String allString = "...";
Pattern pattern = Pattern.compile("I1\\d*");
Matcher matcher = pattern.matcher(allString);
while (matcher.find()) {
System.out.print(matcher.group() + ", ");
}
在Java中,我们也需要转义\
,因此最终模式将变为I1\\d*
。
输出:
I1, I18, I12, I15, I14, I13, I16, I11,
答案 1 :(得分:0)
I1(?!\d)
将匹配I1但不匹配I11,I12等。
String allString = " I1 + I6 + I9 + I8 + I3 + I2 + I20 + I21 + I18 + I23 + I28 + I27 + I31 + I24 + I12 + I15 + I14 + I13 + I16 + I11 ";
Pattern p = Pattern.compile("I1(?!\\d)");
Matcher matcher = p.matcher(allString);
matcher.find();
System.out.println(matcher.group(0));
<强>输出:强>
I1