Smith
Smith

Reputation: 19

Regex to find String which starts with ABC and not ends with XYZ

Please help me here

For below example how do I write the regex to find string which starts with ABC and not ends with XYZ

Example:

ABCfdsAFfadsXYZ ABCffasdffdaAAA FASfdaaffasaAFA

Out of these, only the second one should match.

Upvotes: 1

Views: 4033

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336198

\bABC\w*\b(?<!XYZ)

assuming your regex engine supports lookbehind assertions.

Explanation:

\b        # Start at a word boundary
ABC       # Match ABC
\w*       # Match any number of alphanumeric characters
\b        # End at a word boundary
(?<!XYZ)  # Assert that the previous three characters were not XYZ

Upvotes: 5

Related Questions