【问题标题】:How to find regex match between a special character and the first match of the second character?如何在特殊字符和第二个字符的第一个匹配之间找到正则表达式匹配?
【发布时间】:2019-12-28 03:19:12
【问题描述】:

在熊猫df 的一列中,我有诸如Elgin (west/ouest) (123/456), Ont, CanadaWest/Ouest, Ont, Canada 之类的值,我想通过删除/) 之间的所有字符将它们变成Elgin (west) (123), Ont, CanadaWest, Ont, Canada或在/, 之间。

我的代码:

df_census1901['LOC2'] = df_census1901['LOC'].str.replace(r'/.*\)', ')')
df_census1901['LOC2'] = df_census1901['LOC2'].str.replace(r'/.*\,', ',')

问题是它贪婪地切入Elgin (west), Ont, Canada

【问题讨论】:

  • .*? 使它变得懒惰(非贪婪),这对regex101.com 的每个测试都适用于您的两种场景

标签: regex python-3.x string pandas


【解决方案1】:

在这种情况下,您通常有两种选择:

  • 使用惰性量词*?(或+?)以避免匹配过多:'/.*?\)'
  • 使用否定范围到结束字符的所有内容:'/\[^)\]*)' (这种方法更具体,通常更快)

【讨论】:

    【解决方案2】:

    如果在/ 之后直到), 之前有字母数字值,那么您可以将它们与\w* 匹配,例如:

    print (df_census1901['LOC'].str.replace(r'/\w*', ''))
    0    Elgin (west) (123), Ont, Canada
    1                  West, Ont, Canada
    Name: LOC, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2014-08-12
      相关资源
      最近更新 更多