我有以下数据:
$200 – $4,500
Points – $2,500我想以美元捕获范围,如果是较低的范围,则捕获Points字符串。
例如,如果我在上面的每个条目上运行正则表达式,我希望:
Group 1: 200
Group 2: 4,500和
Group 1: Points
Group 2: 2,500对于第一组,我无法理解如何只捕获整数值(没有$符号),同时允许捕获Points。
以下是我尝试过的:
(?:\$([0-9,]+)|Points) – \$([0-9,]+)发布于 2020-07-30 20:35:39
想出一个与$不匹配的正则表达式并不困难。提出一个与$不匹配的正则表达式,并一致地将这两个值放在一起,无论它们都是数字值还是Points值,因为捕获组1和2并不简单。如果使用命名捕获组,困难就会消失。这个regex需要来自regex存储库的PyPi模块,因为它多次使用相同的命名组。
import regex
tests = [
'$200 – $4,500',
'Points – $2,500'
]
re = r"""(?x) # verbose mode
^ # start of string
(
\$ # first alternate choice
(?P<G1>[\d,]+) # named group G1
| # or
(?P<G1>Points) # second alternate choice
)
\x20–\x20 # ' – '
\$
(?P<G2>[\d,]+) # named group g2
$ # end of string
"""
# or re = r'^(\$(?P<G1>[\d,]+)|(?P<G1>Points)) – \$(?P<G2>[\d,]+)$'
for test in tests:
m = regex.match(re, test)
print(m.group('G1'), m.group('G2'))指纹:
200 4,500
Points 2,500更新
@marianc的评论是正确的,但并没有确保输入中没有多余的字符。因此,有了他的有用投入:
import re
tests = [
'$200 – $4,500',
'Points – $2,500',
'xPoints – $2,500',
]
rex = r'((?<=^\$)\d{1,3}(?:,\d{3})*|(?<=^)Points) – \$(\d{1,3}(?:,\d{3})*)$'
for test in tests:
m = re.search(rex, test)
if m:
print(test, '->', m.groups())
else:
print(test, '->', 'No match')指纹:
$200 – $4,500 -> ('200', '4,500')
Points – $2,500 -> ('Points', '2,500')
xPoints – $2,500 -> No match请注意,由于行开始时执行的查找断言不能成功,所以将执行search而不是match。但是,我们在行的开头不强制执行任何无关的字符,方法是在查找后断言中包含^锚点。
https://stackoverflow.com/questions/63177819
复制相似问题