Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python条件正则表达式_Python_Regex - Fatal编程技术网

Python条件正则表达式

Python条件正则表达式,python,regex,Python,Regex,这是一个涉及python中的条件正则表达式的问题: 我想将字符串“abc”与 match(1)="a" match(2)="b" match(3)="c" match(1)="a" match(2)="" match(3)="" 但是还要将字符串“a”与 match(1)="a" match(2)="b" match(3)="c" match(1)="a" match(2)="" match(3)="" 下面的代码几乎可以做到这一点,问题是在第一种情况下match(1)=“a” 但在第二

这是一个涉及python中的条件正则表达式的问题:

我想将字符串
“abc”

match(1)="a"
match(2)="b"
match(3)="c"
match(1)="a"
match(2)=""
match(3)=""
但是还要将字符串
“a”

match(1)="a"
match(2)="b"
match(3)="c"
match(1)="a"
match(2)=""
match(3)=""
下面的代码几乎可以做到这一点,问题是在第一种情况下
match(1)=“a”
但在第二种情况下,
match(4)=“a”
(而不是根据需要
match(1)

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

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

这将以您想要的方式处理您描述的两种情况,但不一定是通用解决方案。这感觉就像你想出了一个玩具问题,代表了一个真正的问题

很难找到一个通用的解决方案,因为后面元素的处理取决于前面元素和/或相反元素的处理。例如,如果您有完整的
abc
,则初始空格不应存在。如果有初始空格,您应该只找到
a

在我看来,处理这一问题的最佳方法是使用您最初使用的
构造。比赛结束后,您可以编写一些代码,将这些组拉到一个数组中,并根据自己的喜好对它们进行排列

组的规则是,所有未紧跟
?:
的开括号都成为一个组。该组可能是空的,因为它实际上不匹配任何内容,但它将在那里。

可能…:

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
,但在其他未显示的情况下,它可能与您想要的方式不匹配(例如,前面没有空格,或者后面有空格和多个字母,因此匹配字符串的总长度为
!=3
…但我猜在这种情况下您不希望匹配…?)

表达式中的每个捕获组都有自己的索引。请尝试以下操作:

r = re.compile("^\s*(\w)(\w)?(\w)?$")

abc -> ('a', 'b', 'c')
a -> ('a', None, None)
要分解它:

^     // anchored at the beginning
\s*   // Any number of spaces to start with
(\w)  // capture the first letter, which is required
(\w)? // capture the second letter, which is optional
(\w)? // capture the third letter, which is optional
$     // anchored at the end
你是对的,这是仅有的两个案例。正如我所希望的那样。关键是匹配组(\w?)中有“?”,所以要么匹配字母,要么不匹配。谢谢!