Matt Weimer
Matt Weimer

Reputation: 131

Regex: Determine if a character appears before first occurrence of another character

I'm trying to determine whether or not a certain character appears before the first (and only the first) occurrence of another character.

For example, I want to determine whether the character 'X' appears before the first occurrence of 'Y'.

The regex would match these:

acXaaccccYaaacacXacacaY // X appears before the first occurrence of Y
aXacacaXacacXavaY // X appears before the first occurrence of Y

The regex would NOT match this:

acacacaYacacacXacacacY // The X appears after the first occurrence of Y

Is this possible with a single regex match?

Upvotes: 2

Views: 1301

Answers (2)

Bohemian
Bohemian

Reputation: 425238

It is as simple as this:

^[^Y]*X.*Y

If you need to match the whole input, add .*, ie: ^[^Y]*X.*Y.*

See a live demo of this working with your examples.

Upvotes: 3

arshajii
arshajii

Reputation: 129537

You can try something like this:

^[^Y]*X.*Y.*$

In English, that's "A string of non-Ys, then an X, then anything so long as it contains a Y".

Upvotes: 5

Related Questions