Python正在返回不匹配的行

2024-09-26 18:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解决一个正则表达式的难题,我。。。困惑。我希望有以下几点:

import re
import fileinput

TEST_DATA = [
    "6",
    "2 ",
    "1 877 2638277 ",
    "91-011-23413627"
]

for line in TEST_DATA:
    print(
        re.sub(
            r'(\d{1,3})[- ](\d{2,3})[- ]+(\d{5,10})',
            r'CountryCode=\1,LocalAreaCode=\2,Number=\3',
            line))

给我这个:

CountryCode=1,LocalAreaCode=877,Number=2638277 
CountryCode=91,LocalAreaCode=011,Number=23413627

相反,我得到的是:

6
2 
CountryCode=1,LocalAreaCode=877,Number=2638277 
CountryCode=91,LocalAreaCode=011,Number=23413627

我不明白为什么打印不符的行。你知道吗


Tags: intestimportrenumberfordataline
3条回答

re.sub返回字符串,无论是否发生替换。从the documentation

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged.

也许您可以先检查是否发生了match,然后执行替换。你知道吗

for line in TEST_DATA:
    if re.match(my_pattern, line):
        print(
            re.sub(
                r'(\d{1,3})[- ](\d{2,3})[- ]+(\d{5,10})',
                r'CountryCode=\1,LocalAreaCode=\2,Number=\3',
                line))

我得告诉你,我真的很讨厌re.sub。我不知道为什么,我没有一个很好的解释,但我避免它像瘟疫。我甚至不记得用过效果很差的,我只是不喜欢。。。。你知道吗

它不产生预期输出的原因是re.sub将返回字符串,而不管它是否与regex匹配。它有点像"Hello there".replace("foo","bar"),只是因为它找不到任何可以替换的东西,并不意味着它会丢弃你的字符串。我要做的是:

pattern = r'(?P<country>\d{1,3})[- ](?P<area>\d{2,3})[- ]+(?P<number>\d{5,10})'
text = r"CountryCode={country},LocalAreaCode={area},number={number}"

for line in TEST_DATA:
    match = re.match(pattern,line)
    if not match: continue
    print(text.format(**match.groupdict()))

尝试使用:

import re    

TEST_DATA = [
    "6",
    "2 ",
    "1 877 2638277 ",
    "91-011-23413627"
]

pattern = r'(\d{1,3})[- ](\d{2,3})[- ]+(\d{5,10})'
rep = r'CountryCode=\1,LocalAreaCode=\2,Number=\3'

for line in TEST_DATA:
    if re.match(pattern, line):
        print re.sub(pattern,rep,line)

相关问题 更多 >

    热门问题