I need a regex to match any character or word except Q.
I tried using the expression
/\b((?!(Q)).+?)\b/
but it is not working!
Are you trying to forbid the word "Q", or words that include "Q"?
Forbidding words that include "Q"
/\b(?[ \w - [Q] ])+)\b/
This requires use experimental qw( regex_sets );
before 5.36. But it's safe to add this and use the feature as far back as its introduction as an experimental feature in 5.18, since no change was made to the feature since then.
There are alternatives that work before 5.18.
Use double negation: "A character that's (\w and not-Q)" is "a character that's not (not-\w or Q)" ([^\WQ]
).
/\b([^\WQ]+)\b/
You can perform rudimentary set arithmetic using lookarounds (e.g. \w(?<!Q)
).
/b((?:\w(?<!Q))+)\b/
Forbidding the word "Q"
/\b(Q\w+|(?[ \w - [Q] ])+)\w*)\b/
or
/\b(Q\w+|[^\WQ]\w*)\b/
or
/\b(?!Q\b)(\w+)\b/
You can use this regex
\b(?!\w*Q)(\w+)\b
Problems with your regex:
1] (?!Q)
would check if there's Q
after this current position..So with \b(?!Q)
you are checking if a particular word begins with Q
.
You could have used \b(?!\w*Q)
which would check for Q
anywhere withing the word
2] .+?
is making \b
redundant because .
would also match space
.
So if your input is Hello World
with \b.+?\b
regex it would match Hello
,space
,World
.You should use \b\w+\b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With