【发布时间】:2013-12-21 13:20:08
【问题描述】:
我有一个字符串,我想使用正则表达式在其中匹配 B1 和 B2 中的任何一个只出现一次,并且在每个新行的开头。以下是示例和我尝试过的内容:
public static String testStr = "A1ABC 10.101.0 testString \r\n"+
"B100000100111 B18388831993 I am here\r\n";
public static void main(String args[]) {
String regex = "^(B1{1}|B2{1}).*$";
boolean isTrue = testStr.matches(regex);
if (isTrue) {
System.out.println("TRUE returns ......... ");
} else {
System.out.println("FALSE returns ......... ");
}
}
在上述情况下,它应该返回 TRUE,但如果我将输入更改为:
public static String testStr = "A1ABC 10.101.0 testString \r\n"+
"B100000100111 B18388831993 I am here\r\n"+
"B2HELLLOWORLD";
但在上述情况下,它应该返回 FALSE,因为 B1 和 B2 都存在。我想检查 B1 和 B2 中的任何一个仅在行首出现一次,而不是介于两者之间。
我也使用正则表达式:
.*\\r?\\n$^B1{1}.*\\r\\n$ | ^B2{1}.*$
谁能告诉我使用正则表达式的解决方案吗?
【问题讨论】: