我正在尝试了解有关正则表达式的更多信息,我在下面有一个正则表达式,我相信它可以找到在高达 9990 亿的数字上缺少闭括号的情况。我认为它下面的那个应该做同样的事情,但我没有得到类似的结果
missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$")
missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$")
我认为第二个说: 必须有一个开放的 parent 开始
一个美元符号可能有也可能没有
下一组必须至少存在一次,但可以存在无限次
该组应至少有一位数字,但可能有多达三位
该组可能有少至 0 和多至 1 个逗号
这组后面可能有也可能没有小数点
如果有一个小数点,它后面将跟着多达 0 个但不计其数的数字出现
最后不应有右括号。
我正在努力理解这个神奇的东西,所以我希望能对我的正则表达式进行更正(如果可以更正)以及更优雅的解决方案(如果有的话)。
请您参考如下方法:
是否有嵌套的括号(您的正则表达式假设没有)?如果不是:
whether_paren_is_missing = (astring[0] == '(' and not astring[-1] == ')')
验证美元金额部分:
import re
cents = r"(?:\.\d\d)" # cents
re_dollar_amount = re.compile(r"""(?x)
^ # match at the very begining of the string
\$? # optional dollar sign
(?: # followed by
(?: # integer part
0 # zero
| # or
[1-9]\d{,2} # 1 to 3 digits (no leading zero)
(?: # followed by
(?:,\d{3})* # zero or more three-digits groups with commas
| # or
\d* # zero or more digits without commas (no leading zero)
)
)
(?:\.|%(cents)s)? # optional f.p. part
| # or
%(cents)s # pure f.p. '$.01'
)
$ # match end of string
""" % vars())
允许:
$0
0
$234
22
$0.01
10000.12
$99.90
2,010,123
1.00
2,103.45
$.10
$1.
禁止:
01234
00
123.4X
1.001
.
