Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl regex to match any `word character' except Q

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!

like image 914
user2310094 Avatar asked May 15 '13 04:05

user2310094


2 Answers

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/
like image 115
ikegami Avatar answered Oct 04 '22 21:10

ikegami


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

like image 33
Anirudha Avatar answered Oct 04 '22 20:10

Anirudha