Python 条件正则表达式

标签 python regex

这是一道python条件正则表达式题:

我想匹配字符串 "abc"

match(1)="a"
match(2)="b"
match(3)="c"

还要匹配字符串 "a"

match(1)="a"
match(2)=""
match(3)=""

下面的代码几乎就是这样做的,问题是在第一种情况下 match(1)="a" 但在第二种情况下,match(4)="a"(不是所需的match(1))。

事实上,如果您使用 for g in re.search(myre,teststring2).groups(): 遍历所有组,您将得到 6 个组(不是预期的 3 个)。

import re
import sys

teststring1 = "abc"
teststring2 = "  a"

myre = '^(?=(\w)(\w)(\w))|(?=\s{2}(\w)()())'

if re.search(myre,teststring1):
    print re.search(myre,teststring1).group(1)

if re.search(myre,teststring2):
   print re.search(myre,teststring2).group(1)

有什么想法吗? (注意这是针对 Python 2.5 的)

最佳答案

也许……:

import re
import sys

teststring1 = "abc"
teststring2 = "  a"

myre = '^\s{0,2}(\w)(\w?)(\w?)$'

if re.search(myre,teststring1):
    print re.search(myre,teststring1).group(1)

if re.search(myre,teststring2):
   print re.search(myre,teststring2).group(1)

在这两种情况下,这确实会如您所愿地给出 a ,但在您未显示的其他情况下,它可能与您想要的方式不匹配(例如,前面没有空格,或空格 < em> 和 之后超过一个字母,所以匹配字符串的总长度是 != 3...但我只是猜测你 在这种情况下需要匹配...?)

关于Python 条件正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3130209/

相关文章:

c++ - 在 Boost.Python 中公开一个指针

Python IOError : [Errno 90] Message too long, 将长列表传递给 SPI 函数

regex - Pyspark:通过字符串格式的正则表达式过滤数据帧?

javascript - 删除 "unnecessary"空格

php - 重叠匹配 preg_match_all 和以重复字符结尾的模式

regex - 删除行首的数字

python - 随机访问可重新创建的随机生成的大数据

python - 在 Python 3 中确定类的元类

python - 我遇到了有关 AttributeError 的问题

java - Java中的正则表达式无法匹配