字符串regexp中多次出现相同字符 - Python

Rup*_*ton 4 python regex

给出一个由3个大写字母组成的字符串,1个小型大写字母和3个大写字母,例如AAAaAAA

我似乎无法找到一个正则表达式,它会找到一个匹配字符串的字符串:

  • 前三个大写字母都不同
  • 任何小型大写字母
  • 前两个大写字母与第一个相同
  • 最后一个大写字母与第一个"三重奏"中的最后一个大写字母相同

例如A B C a AA C(无空格)

编辑:

结果我需要一些略有不同的东西,例如ABCaAAC,其中'a'是非常拳头角色的小型帽子版本,而不仅仅是任何角色

And*_*ark 11

以下应该有效:

^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$
Run Code Online (Sandbox Code Playgroud)

例如:

>>> regex = re.compile(r'^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$')
>>> regex.match('ABAaAAA')  # fails: first three are not different
>>> regex.match('ABCaABC')  # fails: first two of second three are not first char
>>> regex.match('ABCaAAB')  # fails: last char is not last of first three
>>> regex.match('ABCaAAC')  # matches!
<_sre.SRE_Match object at 0x7fe09a44a880>
Run Code Online (Sandbox Code Playgroud)

说明:

^          # start of string
([A-Z])    # match any uppercase character, place in \1
(?!.?\1)   # fail if either of the next two characters are the previous character
([A-Z])    # match any uppercase character, place in \2
(?!\2)     # fail if next character is same as the previous character
([A-Z])    # match any uppercase character, place in \3
[a-z]      # match any lowercase character
\1         # match capture group 1
\1         # match capture group 1
\3         # match capture group 3
$          # end of string
Run Code Online (Sandbox Code Playgroud)

如果你想从文本较大块拉出这些比赛,刚刚摆脱的^$,并使用regex.search()regex.findall().

但是,您可能会发现以下方法更容易理解,它使用正则表达式进行基本验证,然后使用常规字符串操作来测试所有额外要求:

def validate(s):
    return (re.match(r'^[A-Z]{3}[a-z][A-Z]{3}$', s) and s[4] == s[0] and 
            s[5] == s[0] and s[-1] == s[2] and len(set(s[:3])) == 3)

>>> validate('ABAaAAA')
False
>>> validate('ABCaABC')
False
>>> validate('ABCaAAB')
False
>>> validate('ABCaAAC')
True
Run Code Online (Sandbox Code Playgroud)

  • 你为什么不在改进的模式上使用`r'''....'''和`re.X`? (2认同)