manabreak manabreak - 1 year ago 75
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

, 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 Source

You can use this regex:

  • ^[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]) is negative lookahead to disallow X or Z at start.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download