Reputation: 355
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
Upvotes: 5
Views: 4772
Reputation: 425198
Your problem is the spaces either side of the pipe.
Neither of
" ^.*"
".*$ "
will match anything, because nothing appears before start or after end.
This has a chance:
^[\u0000-\uFFFF]+$|^[^_%]
Upvotes: 0
Reputation: 627082
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:
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
Upvotes: 4
Reputation: 46861
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.
Upvotes: 2