0

I want to match an alphabet range between a and z, except x.

I am using java.util.regex API for this.

My pattern:

[a-z^x] // here a-z shows a range between a to z and ^ means negation 

Example

  • If I type "a", it should match.
  • If I type "x", it shouldn't match
Mena
  • 47,782
  • 11
  • 87
  • 106
Siddharth
  • 117
  • 1
  • 10

1 Answers1

2

You can rewrite your Pattern as follows:

[a-z&&[^x]]

Example

String[] test = {"abcd", "abcdx"};
//                         | range
//                         |   | and
//                         |   | | new class excluding "x"
//                         |   | |    | adding quantifier for this example
Pattern p = Pattern.compile("[a-z&&[^x]]+");
for (String s: test) {
    System.out.println(p.matcher(s).matches());
}

Output

true
false
Mena
  • 47,782
  • 11
  • 87
  • 106