bzibzibzi666
bzibzibzi666

Reputation: 13

REGEX find specific substring if not part of the word

I have troubles with simplifying regex which I created:

@"^sept$|[^a-zA-Z]sept[^a-zA-Z]]|[^a-zA-Z]sept$|^sept[^a-zA-Z]"

That regex has to find substring sept, which is not the part of any word (like september), I receive couple of different variations when word should be found, like:

sept

1sept

sept1

1sept1

sept

... etc.

In my patthern I search for sept which not start/end on letter(so it is not part of different word) and it can be on the start/end of the string. I checked functionality and it meets my needs, but I wonder if there is any better/simplier way to write it.

Upvotes: 1

Views: 1520

Answers (2)

Drizzy
Drizzy

Reputation: 138

[a-zA-z0-9]*(sept|SEPT)[a-zA-z0-9]*

Try above regex.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520948

You can tighten this up by using alternations for the boundary conditions:

(^|[^a-zA-Z])sept($|[^a-zA-Z])

But this would also potentially match one character one each side of sept. To avoid this, you may use lookarounds, assuming your flavor of regex supports them:

(?<=^|[^a-zA-Z])sept(?=$|[^a-zA-Z])

Upvotes: 1

Related Questions