【问题标题】:regex for non alphabets or nothing非字母的正则表达式或什么都没有
【发布时间】:2020-07-30 16:29:52
【问题描述】:


我想从 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' 不包含任何内容。
如何做到这一点?

【问题讨论】:

标签: python regex


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    使用\b 使用正则表达式https://regex101.com/r/2Dlnxj/1 将其设为单词边界

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

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多