Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp to check continuous 3 digits in a string

Tags:

java

regex

I want a regular expression in java to check, if a string contains continuous 3 digits. But the problem is my string may contain unicode characters. If the string contains unicode characters it should skip the unicode characters (skip 4 '.'s after & AND #) and should do the checking. Some examples are

Neeraj : false
Neeraj123 : true
&#1234Neeraj : false
&#1234Neeraj123 : true
123N&#123D : true
Neeraj&#1234 : false
Neeraj&#12DB123 : true
&#1234 : false
like image 856
Neeraj Avatar asked Nov 03 '12 07:11

Neeraj


1 Answers

You need to use a negative 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);

You can use it as follows:

Matcher regexMatcher = regex.matcher(subjectString);
return regexMatcher.find();  // returns True if regex matches, else False
like image 165
Tim Pietzcker Avatar answered Oct 17 '22 01:10

Tim Pietzcker