【问题标题】:Python regex of multiple occurrences of a string of 1+ consecutive chars within a string [duplicate]字符串中多次出现1+连续字符的Python正则表达式[重复]
【发布时间】:2017-07-18 13:42:20
【问题描述】:

我需要找到可变长度字符序列的开始和结束位置,由字符串中的相同 1 个字母组成。 我看到这个话题Finding multiple occurrences of a string within a string in Python,但我认为它有点离题了。

以下内容没有给我任何信息,而我希望找到 5 个元素。

import re
s = 'aaaaabaaaabaaabaaba'
pattern = '(a)\1+'
for el in re.finditer(pattern, s):
    print 'str found', el.start(), el.end()

提前致谢。

【问题讨论】:

标签: python regex string


【解决方案1】:

由于它是一个正则表达式,反斜杠应该在字符串级别进行转义,而应该由正则表达式解释。

您可以使用原始字符串:

import re
s = 'aaaaabaaaabaaabaaba'
pattern = r'(a)\1+'   # raw string
for el in re.finditer(pattern, s):
    print 'str found', el.start(), el.end()

这会生成:

str found 0 5
str found 6 10
str found 11 14
str found 15 17

【讨论】:

  • 非常感谢。标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2011-07-29
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多