Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine whitelist and blacklist in java regex expression

Tags:

java

regex

I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: '_' and '?'

So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]

I need to combine these into one expression.

I have tried the following code, but does not work the way I had hoped:

    String input = "this";
    Pattern p = Pattern
            .compile("^[\u0000-\uFFFF]+$ | ^[^_%]");
    Matcher m = p.matcher(input);
    boolean result = m.matches();
    System.out.println(result);

input: this
actual output: false
desired output: true

like image 589
OneXer Avatar asked Apr 14 '16 09:04

OneXer


2 Answers

You can use character class intersections/subtractions in Java regex to restrict a "generic" character class.

The character class [a-z&&[^aeiuo]] matches a single letter that is not a vowel. In other words: it matches a single consonant.

Use

"^[\u0000-\uFFFF&&[^_%]]+$"

to match all the Unicode characters except _ and %.

More about character class intersections/subtractions available in Java regex, see The Java™ Tutorials: Character Classes.

A test at the OCPSoft Visual Regex Tester showing there is no match when a % is added to the string:

enter image description here

And the Java demo:

String input = "this";
Pattern p = Pattern.compile("[\u0000-\uFFFF&&[^_%]]+"); // No anchors because `matches()` is used
Matcher m = p.matcher(input);
boolean result = m.matches();
System.out.println(result); // => true
like image 123
Wiktor Stribiżew Avatar answered Oct 23 '22 06:10

Wiktor Stribiżew


Here is a sample code to exclude some of characters from a range using Lookahead and Lookbehind Zero-Length Assertions that actually do not consume characters in the string, but only assert whether a match is possible or not.

Sample code: (exclude m and n from range a-z)

    String str = "abcdmnxyz";
    Pattern p=Pattern.compile("(?![mn])[a-z]");
    Matcher m=p.matcher(str);
    while(m.find()){
        System.out.println(m.group());
    }

output:

a b c d x y z

In the same way you can do it.

Regex explanation (?![mn])[a-z]

  (?!                      look ahead to see if there is not:   
    [mn]                     any character of: 'm', 'n' 
  )                        end of look-ahead    
  [a-z]                    any character of: 'a' to 'z'

You can divide the whole range in sub-ranges and can solve the above problem with ([a-l]|[o-z]) or [a-lo-z] regex also.

like image 40
Braj Avatar answered Oct 23 '22 05:10

Braj