views:

51

answers:

1

Hi,

I need to know if a string matches a number of different criterias. I'm trying to solve this by using a regular expression and then see if it matches (in Java: str.matches(myRegex);), but I can't get it right.

The criterias are as follows:

  • The string to match is constructed of 4 letters, [A-Z]
  • It may be preceeded (but not necessarily) by one of "-", "+" or "VC"
  • It shall only match strings containing exactly 4 letters (and the possibly preceeding characters)

Examples:

  • "SHSN" -> match
  • "+SHRA" -> match
  • "VCSHRA" -> match
  • "CAVOK" -> no match
  • "-+SHSN" -> no match

Is this possible to do in one single regex? Or should it be done in code or a combination of the two?

Thanks,

Linus

+7  A: 

Try this regular expression:

^([+-]|VC)?[A-Z]{4}$
Gumbo
+1. But I'd make it a non-capturing group if he doesn't need it to capture: `^(?:[+-]|VC)?[A-Z]{4}$`
T.J. Crowder
Excellent, thank you!I'm not familiar with the term "capturing groups" but will look it up.
aspartame
@aspartame: The matches of non-capturing groups can not be referenced. So you can’t use `group(1)` to get the match of `(?:[+-]|VC)?`.
Gumbo