如何匹配以下正则表达式python?

时间:2012-10-29 23:18:23

标签: python regex

如何将以下内容与正则表达式匹配?

string1 = '1.0) The Ugly Duckling (TUD) (10 Dollars)'
string2 = '1.0) Little 1 Red Riding Hood (9.50 Dollars)'

我正在尝试以下方法:

groupsofmatches = re.match('(?P<booknumber>.*)\)([ \t]+)?(?P<item>.*)(\(.*\))?\(.*?((\d+)?(\.\d+)?).*([ \t]+)?Dollars(\))?', string1)

问题是,当我将它应用于string2时,它工作正常,但是当我将表达式应用于string1时,由于“(TUD)”部分,我无法获得“m.group(name)”。我想使用一个适用于两个字符串的表达式。

我期待:

booknumber = 1.0
item = The Ugly Duckling (TUD)

5 个答案:

答案 0 :(得分:0)

您可以对重复的字符施加更严格的限制:

groupsofmatches = re.match('([^)]*)\)[ \t]*(?P<item>.*)\([^)]*?(?P<dollaramount>(?:\d+)?(?:\.\d+)?)[^)]*\)$', string1)

这将确保数字取自最后一组括号。

答案 1 :(得分:0)

我会把它写成:

num, name, value = re.match(r'(.+?)\) (.*?) \(([\d.]+) Dollars\)', s2).groups()

答案 2 :(得分:0)

你的问题是.*贪婪地匹配,并且它可能消耗太多的字符串。打印所有匹配组将使这更加明显:

import re

string1 = '1.0) The Ugly Duckling (TUD) (10 Dollars)'
string2 = '1.0) Little 1 Red Riding Hood (9.50 Dollars)'

result = re.match(r'(.*?)\)([ \t]+)?(?P<item>.*)\(.*?(?P<dollaramount>(\d+)?(\.\d+)?).*([ \t]+)?Dollars(\))?', string1)

print repr(result.groups())
print result.group('item')
print result.group('dollaramount')

Changing them to *? makes the match the minimum

这在某些RE引擎中可能很昂贵,因此您也可以编写例如\([^)]*\)以匹配所有括号。如果您没有处理大量文本,那可能无关紧要。

不过,你应该使用原始字符串(即r'something')来表示正则表达式,以避免出现令人惊讶的反斜杠行为,并为读者提供线索。

我看到你有这个小组(\(.*?\))?,大概是在删除(TUD),但是如果你真的想在标题中删除它,那就删除吧。

答案 3 :(得分:0)

这就是我使用Demo

的方式

(?P<booknumber>\d+(?:\.\d+)?)\)\s+(?P<item>.*?)\s+\(\d+(?:\.\d+)?\s+Dollars\)

答案 4 :(得分:0)

我建议你使用正则表达式

(?P<booknumber>[^)]*)\)\s+(?P<item>.*\S)\s+\((?!.*\()(?P<amount>\S+)\s+Dollars?\)
相关问题