Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python regex to detect a word exists

I want to detect whether a word is in a sentence using python regex. Also, want to be able to negate it.

import re
re.match(r'(?=.*foo)', 'bar red foo here')

this code works but I do not understand why I need to put .* in there. Also to negate it, I do not know how to do that. I've tried:

re.match(r'(?!=.*foo)', 'bar red foo here')

but it does not work. My ultimate goal is to combine them like so:

re.match(r'(?=.*foo)(?!=.*bar)', 'bar red foo here')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To detect if a word exists in a string you need a positive lookahead:

(?=.*foo)

The .* is necessary to enable searching farther than just at the string start (re.match anchors the search at the string start).

To check if a string has no word in it, use a negative lookahead:

(?!.*bar)
 ^^^

So, combining them:

re.match(r'(?=.*foo)(?!.*bar)', input)

will find a match in a string that contains a whole word foo and does not contain a whole word bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...