freebird2
freebird2

Reputation: 38

Is there a Regex expression to match all occurrences of a letter except in a certain string?

I'm trying to find a Regex expression to match any occurrence of a letter in a string of lowercase [a-z] words, except when that letter is found in a certain word. The words are surrounded by whitespace, barring the first and last word as those are at the start and end of the string.

Specifically, I want to match any 'f' in the string except when found in the word 'def'. I have had very little experience with Regex in the past.

For example, given this string:

'def half def forbidden fluff def def tough off definite def'

the expression should select only the 'f's bolded as such:

'def half def forbidden fluff def def tough off definite def'

Upvotes: 1

Views: 708

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use a PCRE pattern like

(?<!\S)def(?!\S)(*SKIP)(*FAIL)|f

See proof. It matches def inside whitespace boundaries, and skips the match, and matches f in all other places.

enter image description here

If you'd like to make it case insensitive, add (?i):

(?i)(?<!\S)def(?!\S)(*SKIP)(*FAIL)|f

Upvotes: 0

user7571182
user7571182

Reputation:

You may try:

f(?<!\bdef\b)

Explanation of the above regex:

f - Matching f literally.

(?<!\bdef\b) - Represents a negative look-behind not matching any occurrence of the word def. If you want def to be case-insensitive then please use the flag \i.

\b - Represents a word boundary for matching the exact word (in this case def) or characters inside.

Pictorial Representation

You can find the demo of the above regex in here.

Upvotes: 4

Related Questions