正则表达式检查字符串中的连续3位数

时间:2012-11-03 07:22:04

标签: java regex

如果字符串包含连续的3位数字,我想在java中检查正则表达式。但问题是我的字符串可能包含unicode字符。如果字符串包含unicode字符,它应该跳过unicode字符(在& AND#之后跳过4'。)并且应该进行检查。一些例子是

Neeraj : false
Neeraj123 : true
&#1234Neeraj : false
&#1234Neeraj123 : true
123N&#123D : true
Neeraj&#1234 : false
Neeraj&#12DB123 : true
&#1234 : false

1 个答案:

答案 0 :(得分:7)

您需要使用否定lookbehind assertion

Pattern regex = Pattern.compile(
    "(?<!             # Make sure there is no...           \n" +
    " &\\#            # &#, followed by                    \n" +
    " [0-9A-F]{0,3}   # zero to three hex digits           \n" +
    ")                # right before the current position. \n" +
    "\\d{3}           # Only then match three digits.", 
    Pattern.COMMENTS);

您可以按如下方式使用它:

Matcher regexMatcher = regex.matcher(subjectString);
return regexMatcher.find();  // returns True if regex matches, else False