【问题标题】:python regex - totaling number of unique patterns in stringpython regex - 字符串中唯一模式的总数
【发布时间】:2017-08-08 18:57:21
【问题描述】:

如果这是重复的,请原谅我,但我只看到了这么多简单的方法来解决我在两个子字符串之间定位唯一实例总数的问题:'Ha' 和 'ha'

这是我的代码,后面是示例文本:

import re
def ha_counter(laughing):
    if not laughing: 
        return 0
    else:
        return len(re.findall(r'Ha',r'ha'))

如果字符串输入为空,则返回 0,否则提供每个子字符串出现的次数。

Test.assert_equals(ha_counter(""), 0)
Test.assert_equals(ha_counter("hahahahaha"), 1)
Test.assert_equals(ha_counter("hahahahahaHaHaHa"), 2)

【问题讨论】:

  • 你为什么在ha_counter中硬编码r'ha'而不是使用laughing
  • 好点,但 re.findall 是否允许我指定模式 + 但参数 laughing
  • 它期望第一个参数是模式而不是模式,第二个参数是字符串本身。请检查文档而不是想知道它。
  • 制作你的图案r'[Hh]a'。或者没有re - s.lower().count('ha')

标签: python regex string


【解决方案1】:

这可以使用负前瞻来完成:

re.findall(r"Ha(?!.*Ha)","hahahahahaHaHaHa")
Out[5]: ['Ha']

re.findall(r"ha(?!.*ha)","hahahahahaHaHaHa")
Out[6]: ['ha']
#combine the two together with or
re.findall(r"(ha(?!.*ha)|Ha(?!.*Ha))","hahahahahaHaHaHa")
Out[7]: ['ha', 'Ha']

https://regex101.com/r/bk8v1s/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多