The Dude
The Dude

Reputation: 4005

Regular Expression, optional character on multiple locations but result must contain at least once

I am performing a string search where I am looking for the following three strings:

XXX-99-X
XXX-99X
XXX99-X

So far I have:

([A-Z]{3}(-?)[0-9]{2}(-?)[A-Z]{1})

How do I enforce that - has to be present at least once in either of the two possible locations?

Upvotes: 2

Views: 127

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133538

With your shown samples, please try following.

^[A-Z]{3}(?:-?\d{2}-|-\d{2})[A-Z]+$

online demo for above regex

Explanation: Adding detailed explanation for above.

^[A-Z]{3}        ##Matching if value starts with 3 alphabets here.
(?:              ##Starting a non capturing group here.
   -?\d{2}-      ##Matching -(optional) followed by 2 digits followed by -
   |
   -\d{2}        ##Matching dash followed by 2 digits.
)                ##Closing very first capturing group.
[A-Z]+$          ##Matching 1 or more occurrences of capital letters at the end of value.

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163362

You might use an alternation, to match either a - and optional - at the left or - at the right part.

Note that you can omit {1} from the pattern.

^[A-Z]{3}(?:-[0-9]{2}-?|[0-9]{2}-)[A-Z]$
  • ^[A-Z]{3}
  • (?: Non capture group
    • -[0-9]{2}-?|[0-9]{2}- Match either - 2 digits and optional - Or 2 digits and -
  • ) Close non capture group
  • $ end of string

regex demo

Or use a positive lookahead to assert a - at the right

^(?=[^-\r\n]*-)[A-Z]{3}-?[0-9]{2}-?[A-Z]$
  • ^ Start of string
  • (?=[^-\r\n]*-) Positive lookahead, assert a - at the right
  • [A-Z]{3}-? Match 3 chars A-Z and optional -
  • [0-9]{2}-? Match 2 digits and optional -
  • [A-Z] Match a single char A-Z
  • $ End of string

Regex demo

Upvotes: 2

Related Questions