3

我有大量格式为 YYYYYYYYXXXXXXXXZZZZZZZZ 的字符串,其中 X、Y 和 Z 是固定长度的数字,八位数。现在,问题是我需要解析出中间的整数序列并删除任何前导零。不幸的是,确定三个序列中每一个的开始/结束位置的唯一方法是计算位数。

我目前分两步进行,即:

m = re.match(
    r"(?P<first_sequence>\d{8})"
    r"(?P<second_sequence>\d{8})"
    r"(?P<third_sequence>\d{8})",
    string)
second_secquence = m.group(2)
second_secquence.lstrip(0)

哪个确实有效,并给了我正确的结果,例如:

112233441234567855667788 --> 12345678
112233440012345655667788 --> 123456
112233001234567855667788 --> 12345678
112233000012345655667788 --> 123456

但是有更好的方法吗?是否可以编写一个与第二个序列匹配的正则表达式,没有前导零?

我想我正在寻找执行以下操作的正则表达式:

  1. 跳过前八位数字。
  2. 跳过任何前导零。
  3. 之后捕获任何内容,直到后面有 16 个字符/前面有 8 个字符。

如前所述,上述解决方案确实有效,所以这个问题的目的更多是为了提高我对正则表达式的了解。我很感激任何指示。

4

4 回答 4

4

这是“无用的正则表达式”的典型案例。

你的字符串是固定长度的。只需将它们切割在适当的位置即可。

s = "112233440012345655667788"
int(s[8:16])
# -> 123456
于 2016-12-07T13:54:43.547 回答
3

我认为不使用正则表达式更简单。

result = my_str[8:16].lstrip('0')
于 2016-12-07T13:53:48.627 回答
2

同意这里的其他答案,即真正不需要正则表达式。如果您真的想使用正则表达式,那么\d{8}0*(\d*)\d{8}应该这样做。

于 2016-12-07T13:58:42.650 回答
1

只是为了表明使用正则表达式是可能的:

https://regex101.com/r/8RSxaH/2

# CODE AUTO GENERATED BY REGEX101.COM (SEE LINK ABOVE)
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?<=\d{8})((?:0*)(\d{,8}))(?=\d{8})"

test_str = ("112233441234567855667788\n"
    "112233440012345655667788\n"
    "112233001234567855667788\n"
    "112233000012345655667788")

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

虽然你并不真的需要它来做你所要求的

于 2016-12-07T14:01:35.593 回答