首页 > 解决方案 > 非字母的正则表达式或什么都没有

问题描述


我想从 python 字符串中识别“如何”。

string1
how to find
it is a show
okay how to


用过的:

df[df['string1'].str.contains("how",case=False)]

输出来:

string1
how to find
it is a show
okay how to

因为“show”包含“how”

需要的输出:

string1
how to find
okay how to

之后我用

df[df['string1'].str.contains(r"\Whow",case=False)]

但我得到的输出是:

string1
okay how to

这又是磨损的。
正则表达式 '\W' 不包含任何内容。
如何做到这一点?

标签: pythonregex

解决方案


您需要该模式的边界(\b),否则它也会匹配单词中包含的子字符串:

df[df['string1'].str.contains(r"\bhow\b",case=False)]

      string1
1    how to find
3    okay how to
dtype: object

推荐阅读