Regex expression for strings

Viewed 72

I need a regex that matches a string with the following specifications:

> At least one alpha-numeric character, followed by one or zero '?' or one or zero '!', but does not contain both '?' and '!'. Examples of valid strings: 'xyz', 'zy!', 'Xy?'

I have come up with this so far, which does not work:

[0-9]|[a-z] + ?! + ?? ^[^<>]+$
1 Answers

One option could be repeating a character class [A-Za-z0-9]+ 1+ times followed by matching an optional question or exclamation mark using another character class [?!]?

To prevent being part of a larger word you might start the pattern with a wordboundary \b and end asserting (?!\S) not a non whitespace char on the right.

\b[A-Za-z0-9]+[?!]?(?!\S)

Regex demo

To match the exact string only you might use anchors ^ to assert the start and $ end of the string.

^[A-Za-z0-9]+[?!]?$

Regex demo

Related