manabreak manabreak - 1 month ago 7
Java Question

Java Regex: Allow only certain characters, but don't allow certain characters to begin the string?

I'm fiddling around with Java regex, and I'm trying to come up with a pattern that allows a certain set of characters anywhere else BUT it can't start with certain characters in the allowed set.

For example, let's say the allowed characters are from A to Z, but the string can't start with X or Z. How do I do that? I've come up with

^[XZ][^A-Z]+
, and while it works otherwise, it allows the string to start with other letters that are not in the set (e.g. with punctuation).

Answer

You can use this regex:

^[A-WY][A-Z]*$
  • ^[A-WY] ensures that the first character is A-W or Y
  • [A-Z]*$ will match 0 or more of any uppercase English letter

In general to exclude certain characters you can also use negative look-ahead:

^(?![XZ])[A-Z]+$

(?![XZ]) is negative lookahead to disallow X or Z at start.

Comments