Reputation: 38
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
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.
If you'd like to make it case insensitive, add (?i)
:
(?i)(?<!\S)def(?!\S)(*SKIP)(*FAIL)|f
Upvotes: 0
Reputation:
You may try:
f(?<!\bdef\b)
Explanation of the above regex:
f
- Matchingf
literally.
(?<!\bdef\b)
- Represents a negative look-behind not matching any occurrence of the worddef
. If you wantdef
to be case-insensitive then please use the flag\i
.
\b
- Represents a word boundary for matching the exact word (in this casedef
) or characters inside.
You can find the demo of the above regex in here.
Upvotes: 4