python - 字符串正则表达式中多次出现相同字符 - Python

标签 python regex

给定一个由 3 个大写字母、1 个小型大写字母和另外 3 个大写字母组成的字符串, 例如啊啊啊啊

我似乎无法找到一个正则表达式来找到一个与具有以下字符串的字符串相匹配的字符串:

  • 前3个大写字母都不一样
  • 任何小型大写字母
  • 前 2 个与第一个相同的大写字母
  • 最后一个大写字母与第一个“三重奏”中的最后一个大写字母相同

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

编辑:

原来我需要一些稍微不同的东西,例如ABCaAAC 其中 'a' 是 非常拳头字符的小型大写版本,不只是任何字符

最佳答案

以下应该有效:

^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$

例如:

>>> 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>

解释:

^          # 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

如果您想从更大的文本 block 中提取这些匹配项,只需去掉 ^$ 并使用 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

关于python - 字符串正则表达式中多次出现相同字符 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9795955/

相关文章:

c - 如何在 Perl API 中内省(introspection)正则表达式

python - Django 用户 session 、Cookie 和超时

Python 正则表达式 - 限制结果?

python - 如何在 Python 中将测量的发射线数据与高斯函数拟合? (原子光谱)

php - 匹配文本 block 到第一个双新行的正则表达式?

java - PDI 勺子步骤中的 HTML 抓取(用户定义的 java 类)

javascript - 具有动态要求的正则表达式

python - 如何将普通引号转换为 Guillemets(法语引号),标签除外

python - Pickle 可以处理大于我机器上安装的 RAM 的文件吗?

python - 处理错误和异常的Python方式