下面是我的程序
public class StringMatchesTester {
public static void main(String[] args) {
String[] test = new String[] { "CHN_abcd", "CNC_ddd", "_CHN_abcd",
"kunming","CMN" };
String regex = "^[^(CHN|CNC)].*$";
for (int i = 0; i < test.length; i++) {
String temp = test[i];
System.out.println(temp + "-------->matches(" + regex + ")="
+ temp.matches(regex));
}
}
}
我的目的是用正则表达式匹配所有不是以“CHN”或“CNC”开头的字符串。可是却将以“CMN”开头的字符串也给过滤掉了。
以下是程序的输出:
CHN_abcd-------->matches(^[^(CHN|CNC)].*$)=false
CNC_ddd-------->matches(^[^(CHN|CNC)].*$)=false
_CHN_abcd-------->matches(^[^(CHN|CNC)].*$)=true
kunming-------->matches(^[^(CHN|CNC)].*$)=true
CMN-------->matches(^[^(CHN|CNC)].*$)=false
请各位指点迷津,看看我问题出在哪里了?
先给大家鞠躬了!
public class StringMatchesTester {
public static void main(String[] args) {
String[] test = new String[] { "CHN_abcd", "CNC_ddd", "_CHN_abcd",
"kunming","CMN" };
String regex = "^[^(CHN|CNC)].*$";
for (int i = 0; i < test.length; i++) {
String temp = test[i];
System.out.println(temp + "-------->matches(" + regex + ")="
+ temp.matches(regex));
}
}
}
我的目的是用正则表达式匹配所有不是以“CHN”或“CNC”开头的字符串。可是却将以“CMN”开头的字符串也给过滤掉了。
以下是程序的输出:
CHN_abcd-------->matches(^[^(CHN|CNC)].*$)=false
CNC_ddd-------->matches(^[^(CHN|CNC)].*$)=false
_CHN_abcd-------->matches(^[^(CHN|CNC)].*$)=true
kunming-------->matches(^[^(CHN|CNC)].*$)=true
CMN-------->matches(^[^(CHN|CNC)].*$)=false
请各位指点迷津,看看我问题出在哪里了?
先给大家鞠躬了!
CNC_ddd-------->matches(^[^(CHN|CNC)].*$)=false
_CHN_abcd-------->matches(^[^(CHN|CNC)].*$)=true
kunming-------->matches(^[^(CHN|CNC)].*$)=true
CMN-------->matches(^[^(CHN|CNC)].*$)=false
不要用中括号圈住 中括号里面的全部是按单个字分析的
(?:CHN|CNC)[^\s]*
这样就可以了
String regex = "^(?!(CHN|CNC)).*$";