【问题标题】:Combined regex pattern to match beginning and end of string and remove a separator character组合正则表达式模式以匹配字符串的开头和结尾并删除分隔符
【发布时间】:2021-02-08 15:13:13
【问题描述】:

我有以下字符串:

"LP, bar, company LLP, foo, LLP"
"LLP, bar, company LLP, foo, LP"
"LLP,bar, company LLP, foo,LP"  # note the absence of a space after/before comma to be removed

我正在寻找一个接受这些输入并返回以下内容的正则表达式:

"LP bar, company LLP, foo LLP"
"LLP bar, company LLP, foo LP"
"LLP bar, company LLP, foo LP"

我这么胖的是这样的:

import re

def fix_broken_entity_names(name):
    """
    LLP, NAME -> LLP NAME
    NAME, LP -> NAME LP
    """
    pattern_end = r'^(LL?P),'
    pattern_beg_1 = r', (LL?P)$'
    pattern_beg_2 = r',(LL?P)$'
    combined = r'|'.join((pattern_beg_1, pattern_beg_2, pattern_end))
    return re.sub(combined, r' \1', name)

当我运行它时:

>>> fix_broken_entity_names("LP, bar, company LLP, foo,LP")
Out[1]: '  bar, company LLP, foo '

我会非常感谢任何提示或解决方案:)

【问题讨论】:

    标签: python regex regex-group python-re


    【解决方案1】:

    你可以使用

    import re
    texts = ["LP, bar, company LLP, foo, LLP","LLP, bar, company LLP, foo, LP","LLP,bar, company LLP, foo,LP"]
    for text in texts:
        result = ' '.join(re.sub(r"^(LL?P)\s*,|,\s*(LL?P)$", r" \1\2 ", text).split())
        print("'{}' -> '{}'".format(text, result))
    

    输出:

    'LP, bar, company LLP, foo, LLP' -> 'LP bar, company LLP, foo LLP'
    'LLP, bar, company LLP, foo, LP' -> 'LLP bar, company LLP, foo LP'
    'LLP,bar, company LLP, foo,LP' -> 'LLP bar, company LLP, foo LP'
    

    查看Python demoregex^(LL?P)\s*,|,\s*(LL?P)$

    • ^(LL?P)\s*, - 字符串开头,LLPLP(第 1 组),零个或多个空格,逗号
    • | - 或
    • ,\s*(LL?P)$ - 逗号、零个或多个空格、LPLLP(第 2 组),然后是字符串。

    请注意,替换是包含在单个空格内的第 1 组和第 2 组值的串联,后处理步骤是删除所有前导/尾随空格并将字符串内的空格缩小为单个空格。

    【讨论】:

    • 看起来 regex101 演示保留了太多空格
    • @MonkeyZeus 当然,这就是 Python 在这里有很大帮助的原因:后处理步骤是删除所有前导/尾随空格并将字符串中的空格缩小为单个空格 .
    • 哦,原来如此,.split()等的使用...?
    • @MonkeyZeus 这是一个" ".join(list_here) 成语。
    【解决方案2】:

    利用捕获组并根据需要重新格式化:

    正则表达式:

    ([^,\r\n]+) *, *([^,\r\n]+) *, *([^,\r\n]+) *, *([^,\r\n]+) *, *([^,\r\n]+)
    

    替换

    \1 \2, \3, \4 \5
    

    https://regex101.com/r/jcEzzy/1/

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 2015-04-27
      • 1970-01-01
      • 2014-05-14
      • 2022-08-03
      • 1970-01-01
      • 2023-01-02
      • 2013-08-04
      • 1970-01-01
      相关资源
      最近更新 更多