我有一些未指定的长度,后跟一个 15 位数字。
例如:
(未指定长度的随机数)+ 15 位数字 --> 3 + 15 位数字
(未指定长度的随机数)+ 15 位数字 --> 32831 + 15 位数字
(未指定长度的随机数)+ 15 位数字 --> 31 + 15 位数字
我可以在 Python 中使用 RegEx 来捕获“第 1 部分”(长度不确定)和最后 15 位数字作为“第 2 部分”吗?
在我看来,除了最后 15 个字符之外,您只需要所有内容,为什么要为这个简单的任务使用正则表达式?我们可以简单地获取字符串的一部分(如果之前是数字,只需转换为字符串,执行此操作,然后再转换回来):
>>> a = "3123456789123456" #3 + 15 digit number
>>> (a[:-15], a[-15:])
('3', '123456789123456')
>>> a = "32831123456789123456" #32831 + 15 digit number
>>> (a[:-15], a[-15:])
('32831', '123456789123456')
>>> a = "31123456789123456" #31 + 15 digit number
>>> (a[:-15], a[-15:])
('31', '123456789123456')
好,易于。
试试这个正则表达式:
^(\d+)(\d{15})$
解释:
^ Start of string
$ End of string
\d Any digit
{15} Repeat 15 times
+ Repeat one or more times.
(...) Capturing group
当然,使用 regex(\d*)(\d{15})
或矫枉过正(?<!\d)(\d*)(\d{15})(?!\d)