Red
Red

Reputation: 2246

Regex for this particular pattern

I have three different things

xxx
xxx>xxx
xxx>xxx>xxx

Where xxx can be any combination of letters and number

I need a regex that can match the first two but NOT the third.

Upvotes: 1

Views: 66

Answers (2)

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

To match ASCII letters and digits try the following:

^[a-zA-Z0-9]{3}(>[a-zA-Z0-9]{3})?$

If letters and digits outside of the ASCII character set are required then the following should suffice:

^[^\W_]{3}(>[^\W_]{3})?$

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336308

^\w+(?:>\w+)?$

matches an entire string.

\w+(?:>\w+)?\b(?!>)

matches strings like this in a larger substring.

If you want to exclude the underscore from matching, you can use [\p{L]\p{N}] instead (if your regex engine knows Unicode), or [^\W_] if it doesn't, as a substitute for \w.

Upvotes: 1

Related Questions