Python Regex - 将多个表达式与组匹配

时间:2013-07-30 01:17:52

标签: python regex

我有一个字符串:

property1=1234, property2=102.201.333, property3=abc

我想捕获1234和102.201.333。我正在尝试使用正则表达式:

property1=([^,]*)|property2=([^,]*)

但它只设法捕获其中一个值。基于 this link ,我也尝试过:

((?:property1=([^,]*)|property2=([^,])+)
(?:(property1=([^,]*)|property2=([^,])+)

他们从某个我无法想象的地方捕获了一个额外的小组。

我错过了什么?

P.S。我正在使用re.search()。

编辑:我的调用代码可能有问题:

m = re.search('property1=([^,]*)|property2=([^,]*)', text);
print m.groups()

Edit2:它不一定是propertyX。它可以是任何东西:

foo1=123, bar=101.2.3, foobar=abc

甚至

foo1=123, bar=weirdbar[345], foobar=abc

6 个答案:

答案 0 :(得分:1)

作为替代方案,我们可以使用一些字符串拆分来创建字典。

text = "property1=1234, property2=102.201.333, property3=abc"
data = dict(p.split('=') for p in text.split(', '))
print data["property2"] # '102.201.333'

答案 1 :(得分:1)

正则表达式非常适合像lexemes这样的事情,对于通用解析不太好。

在这种情况下,看起来你的“configuration-y string”可能只包含一系列形式的词汇: word {{1} } value [= word , value ...]。如果是这样,您可以使用正则表达式和重复。正确的正则表达式取决于 word value 的确切形式(但在较小程度上,是否要检查错误)。例如,是:

=

是否允许?如果是,this="a string with spaces", that = 42, quote mark = " 设置为this(无引号)或a string with spaces(包括引号)? "a string with spaces"设置为that(前导空白)还是 42(不是){是否允许42(具有嵌入空格),是否设置为双引号?双引号(如果存在),“转义”逗号,以便您可以写:

quote mark

假设禁止使用空格,部分只是“由greeting="Hello, world." 匹配的字母数字”:

\w

for word, value in re.findall(r'([\w]+)=([\w]+)', string): print word, value 值可以清楚地看出102.201.333不足以进行\w匹配。如果 value 是“一切都不是逗号”(包括空格),那么:

value

越来越近了。这些都忽略了“垃圾”并禁止for word, value in re.findall(r'([\w]+)=([^,]+)', string): print word, value 符号周围的空格。如果=string,则会打印第二个"$a=this, b = that, c=102.201.333,,"循环:

for

忽略美元符号(不是字母数字字符),由于空格而忽略a this c 102.201.333 的值,并忽略b值之后的两个逗号。< / p>

答案 2 :(得分:0)

您正在使用|。这意味着你的正则表达式将匹配条形图左侧的东西或右侧的东西。

答案 3 :(得分:0)

你可以尝试:

property_regex = re.compile('property[0-9]+=(?P<property_value>[^\s]+)')

将匹配等号后面和空格前的任何属性。它可以从名称property_value访问,就像文档说的那样:

python re documentation

复制
  

例如,如果模式是(?P [a-zA-Z _] \ w *),则该组可以是   在匹配对象的方法的参数中由其名称引用,例如   如m.group('id')或m.end('id'),以及常规名称   表达式本身(使用(?P = id))和.sub()的替换文本   (使用\ g)。

答案 4 :(得分:0)

试试这个:

property_regex = re.compile('property[0-9]+=([^\s]+)')

答案 5 :(得分:0)

我已经尝试为你构建一个正则表达式,它会在property1 =和property2之后为你提供值,但我不确定你是如何在Python中使用它们的。

修改

现在在“=”符号之前捕获除属性之外的其他内容。

这是我原来的正则表达式,它确实捕获了值。

?(?&LT = [\ W] =)* [^,] +

这是以上的变体,IMO我相信你需要在Python中使用

/(?<=[\w]=).*?[^,]+/g