Python 重新返回不匹配的行

标签 python regex

我正在尝试解决一个正则表达式难题,但我……很困惑。我期待以下内容:

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

我不明白为什么要打印不匹配的行。

最佳答案

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))

关于Python 重新返回不匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865001/

相关文章:

javascript - JS/正则表达式 : How to set group in a regex for multiple replacement?

python - 如何将 Numpy 数组添加到字典中

regex - html5 模式匹配 float 和/或百分比

正则表达式仅替换 gedit 中的一部分

regex - Grep:省略搜索和结果之间的空格

RegEx - 是否可以仅使用 RegEx 引擎进行递归替换?条件搜索替换

python - conda 错误 : Cannot link a source that does not exist

python - 《Think Python : How to Think Like a Computer Scientist》》习题9.3有没有更好的算法

python - 使用pandas制作pivot_table但出现错误

python - TextMate 中 Python 的用户输入