天天看点

正则表达式 学习笔记2.2

排除型字符组:

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

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

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

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);

}

if(regexMatch(hexDigit,negativeDigitRegex2)){

System.out.println("16进制数值:" + hexDigit +"能够匹配正则2:" + negativeDigitRegex2);

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 {

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);

System.out.println(string +"不能够能够匹配正则:" + regex);

case不能够匹配正则:cas[^e]

casa能够匹配正则:cas[^e]

caso能够匹配正则:cas[^e]

cas不能够匹配正则:cas[^e]

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

注意:

排除型字符组的意思是:匹配未列出的字符,而不是“不匹配这个字符”

例如:cas[^e]匹配cas并且不为e的字符

未完待续。。。

本文转自jooben 51CTO博客,原文链接:http://blog.51cto.com/jooben/317153

继续阅读