您的位置:首页 > 其它

正则表达式 学习笔记2.2

2010-05-17 21:01 232 查看
排除型字符组:

作用:规定某个位置不容许出现的字符

形式:以[^...]给出,在方括号内列出不容许出现的字符

排除型字符组仍然必须匹配一个字符,不能匹配空字符

public class GeneralNumThree {
public static void main(String[] args) {
String[] hexDigits = new String[] { "0", "1", "2", "3","4","5","6","7","8","9",
"a", "b", "c", "d","e","f"};
String negativeDigitRegex = "[^0-5]";
String negativeDigitRegex2 = "[^0-5e-f]";

for (String hexDigit : hexDigits) {
if(regexMatch(hexDigit,negativeDigitRegex)){
System.out.println("16进制数值:" + hexDigit +"能够匹配正则1:" + negativeDigitRegex);
}else{
System.out.println("16进制数值:" + hexDigit +"不能够能够匹配正则1:" + negativeDigitRegex);
}
}

for (String hexDigit : hexDigits) {
if(regexMatch(hexDigit,negativeDigitRegex2)){
System.out.println("16进制数值:" + hexDigit +"能够匹配正则2:" + negativeDigitRegex2);
}else{
System.out.println("16进制数值:" + hexDigit +"不能够能够匹配正则2:" + negativeDigitRegex2);
}
}
}
private static boolean regexMatch(String s, String regex) {
return s.matches(regex);
}
}
第一个排除0-5之间数字,第二个排除0-5和e-f之间。

运行结果:
0不能够匹配正则1:[^0-5]
1不能够匹配正则1:[^0-5]
2不能够匹配正则1:[^0-5]
3不能够匹配正则1:[^0-5]
4不能够匹配正则1:[^0-5]
5不能够匹配正则1:[^0-5]
6能够匹配正则1:[^0-5]
7能够匹配正则1:[^0-5]
8能够匹配正则1:[^0-5]
9能够匹配正则1:[^0-5]
a能够匹配正则1:[^0-5]
b能够匹配正则1:[^0-5]
c能够匹配正则1:[^0-5]
d能够匹配正则1:[^0-5]
e能够匹配正则1:[^0-5]
f能够匹配正则1:[^0-5]
0不能够匹配正则2:[^0-5e-f]
1不能够匹配正则2:[^0-5e-f]
2不能够匹配正则2:[^0-5e-f]
3不能够匹配正则2:[^0-5e-f]
4不能够匹配正则2:[^0-5e-f]
5不能够匹配正则2:[^0-5e-f]
6能够匹配正则2:[^0-5e-f]
7能够匹配正则2:[^0-5e-f]
8能够匹配正则2:[^0-5e-f]
9能够匹配正则2:[^0-5e-f]
a能够匹配正则2:[^0-5e-f]
b能够匹配正则2:[^0-5e-f]
c能够匹配正则2:[^0-5e-f]
d能够匹配正则2:[^0-5e-f]
e不能够匹配正则2:[^0-5e-f]
f不能够匹配正则2:[^0-5e-f]

例子:
public class GeneralNumFour {
public static void main(String[] args) {
String[] strings = new String[] { "case", "casa", "caso", "cas"};
String regex = "cas[^e]";
for (String string : strings) {
if(regexMatch(string,regex)){
System.out.println(string +"能够匹配正则:" + regex);
}else{
System.out.println(string +"不能够能够匹配正则:" + regex);
}
}
}
private static boolean regexMatch(String s, String regex) {
return s.matches(regex);
}
}

运行结果:
case不能够匹配正则:cas[^e]
casa能够匹配正则:cas[^e]
caso能够匹配正则:cas[^e]
cas不能够匹配正则:cas[^e]

cas的情况,就是说排除型字符^e不能匹配任意一个字符,所以整个正则表达式的匹配失败。

注意:
排除型字符组的意思是:匹配未列出的字符,而不是“不匹配这个字符”
例如:cas[^e]匹配cas并且不为e的字符

未完待续。。。本文出自 “lee” 博客,请务必保留此出处http://jooben.blog.51cto.com/253727/317153
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: