我得到一个 15 位数字的输入字符串,即 001230123456789
。
它有两个数字 - 第一个是 00123
(最少 1 个非零数字,最多 5 个数字),第二个是 0123456789
(最少 100000000
,最多 10 位)。捕获的输出(那些数字)不应包含前导零。
(在 Python 中)更简单且可能是唯一正确的方法是数组切片和 lstrip():
input = "001230123456789"
output = [(input[:5].lstrip('0'), input[5:].lstrip('0'))]
# ('123', '123456789')
但我的任务是用正则表达式做同样的事情。
无论我是否尝试过贪心选项,我都坚持保留 zome zeros。
我以那个结尾:0{0,4}([1-9]\d{0,4})0?([1-9]\d{8,9})
它通过了我 3/6 的测试:
000010111111111 - ('10', '111111111') (should be ('1', '111111111'))
116402151672479 - OK ('11640', '2151672479')
006421651672479 - ('6421', '651672479') (should be ('642', '1651672479'))
712120751672479 - OK ('71212', '751672479')
712121551672479 - OK ('71212', '1551672479')
006400351672479 - ('6400', '351672479') (should be ('640', '351672479'))
有没有什么办法只用一个正则表达式就可以做到这一点?
在 pastie.org 上带有测试和预期值的完整示例源代码。
最佳答案
给你。
/^0*(\d{1,5})(?<=.{5})(?<!00000)(?!00)(?=\d{10}$)0*(.+)/
| | | | | | | |
| | | | | | | capture 2nd number
| | | | | | |
| | | | | | chomp leading zeroes
| | | | | |
| | | | | assert there're 10 digits ahead
| | | | |
| | | | assert second part at least 100000000
| | | |
| | | make sure first part at least one nonzero digit
| | |
| | assert there are 5 chars behind (already tested numeric)
| |
| capture 1st number (don't worry; the assertions will fix this up)
|
chomp leading zeroes (i'm going to line up these comments damn it!)
这是 a Rubular demo .
((?:^|\s)
和 (?:\s|$)
仅用于展示目的。)
结果如下:
000010111111111 --> 1 111111111
116402151672479 --> 11640 2151672479
006421651672479 --> 642 1651672479
712120751672479 --> 71212 751672479
712121551672479 --> 71212 1551672479
006400351672479 --> 640 351672479
# not enough digits
71212155167247 --> no match
# too many digits
7121215516724798 --> no match
# first part == 0
000001551672479 --> no match
# second part < 100,000,000
712120098765479 --> no match
关于python - 用两个固定长度的数字对正则表达式进行分组并删除其前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12323402/