2013-04-07 143 views
15

我无法找到正确的正则表达式如下场景:Python正则表达式匹配整个单词

比方说:

a = "this is a sample" 

我想全字匹配 - 比如比赛"hi"应由于"hi"不是单词,因此"is"应该返回True,因为左侧和右侧没有字母字符。

+0

我重新打开了这个问题,因为它被错误的帖子重复封闭。 – 2017-04-26 09:02:32

回答

23

尝试

re.search(r'\bis\b', your_string) 

the docs

\ b匹配空字符串,但只在一个单词的开头或结尾。

注意,re模块使用“字”的幼稚定义为“字母数字的序列或下划线字符”,其中“字母数字”依赖于语言环境或Unicode选项。

+2

谢谢,我添加了flags = re.IGNORECASE – user2161049 2013-04-07 14:06:36

+1

这不适用于word =“test!” The!打破它。 – user2161049 2013-04-07 14:11:49

+0

在本声明中需要什么** r ** --re.search(** r **'\ bis \ b',your_string)? – swordholder 2013-10-08 10:46:16

-4

用正则表达式麻烦的是,如果你要搜索在另一个字符串中有正则表达式字符字符串兴田就变得复杂。任何带括号的字符串都会失败。

该代码会发现一个字

word="is" 
    srchedStr="this is a sample" 
    if srchedStr.find(" "+word+" ") >=0 or \ 
     srchedStr.endswith(" "+word): 
     <do stuff> 

与各侧的空间,而第二部分的文字条件搜索的第一部分捕获的字符串状况的结束。需要注意的是ENDWITH是布尔值,而find返回一个整数

+2

这是难以阅读,请编辑。 – davejagoda 2015-11-05 04:21:59

+1

另外,我看到已经有一个被接受的答案 - 你可能想要删除你的答案并由于downvote而恢复声望。 – davejagoda 2015-11-05 04:23:34

+0

@davejagoda将删除答案恢复他/她的声誉? – 2015-11-05 04:41:38

1

在正则表达式试试这个使用文字边界:

>>> x="this is a sample" 
>>> y="this isis a sample." 
>>> regex=re.compile(r"\bis\b") # For ignore case: re.compile(r"\bis\b", re.IGNORECASE) 
>>> regex.findall(y) 
[] 
>>> regex.findall(x) 
['is'] 

re.search()文档。

It matches the empty string, but only at the beginning or end of a word 

E.g. r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3' 

希望它有帮助!