perl regex to match any `word character' except Q
Asked Answered
S

2

5

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!

Strike answered 15/5, 2013 at 4:20 Comment(0)
K
12

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/
Kalindi answered 15/5, 2013 at 4:24 Comment(1)
ABSOLUTELY BRILLIANT use of boolean logic there. I wish I could give more upvotes!Polad
K
1

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

Kriss answered 15/5, 2013 at 4:30 Comment(3)
The last paragraph is wrong. 'Hello World' =~ /\b.+?\b/ just matches Hello.Kalindi
@Kalindi it is correct..I have tested it..you have to find it not matchKriss
Test showing it matches just Hello.Kalindi

© 2022 - 2024 — McMap. All rights reserved.