【问题标题】:Using Regex in Python to add PartNoId identifier before PartNo-在 Python 中使用 Regex 在 PartNo- 之前添加 PartNoId 标识符
【发布时间】:2021-07-16 03:03:03
【问题描述】:

我在 Python 中使用 Regex 在 PartNo- 之前添加 PartNoId 标识符。

正在使用的代码如下:

import re
def process_PartNo(text):    
    text = re.sub(r'(PartNo-)', r'PartNoId \1', text, flags=re.IGNORECASE|re.DOTALL)
    return text
#######################################################################################
text1 = 'PartNo-001A description 20 units some other description'
text2 = 'PartNoId PartNo-001A description QtyOrd 20 some other description'
text3 = '''
PartNoId
PartNo-001A description QtyOrd 20'
'''
text4 = '''
PartNoId

PartNo-001A description QtyOrd 20'
'''
text5 = ''' 
PartNoId PartNo-001A description QtyOrd 20 some other description
PartNoId PartNo-002A description QtyOrd 20 some other description 
'''
text6 = ''' 
PartNo-001A description QtyOrd 20 some other description
PartNo-002A description QtyOrd 20 some other description 
'''
###########################################################################
print(process_PartNo(text1))
print(process_PartNo(text2))
print(process_PartNo(text3))
print(process_PartNo(text4))
print(process_PartNo(text5))
print(process_PartNo(text6))

但是如果已经存在 PartNoId 已经存在的大量文本,则不应再次添加 PartNoId

输出的代码如下:

PartNoId PartNo-001A description 20 units some other description
PartNoId PartNoId PartNo-001A description QtyOrd 20 some other description

PartNoId
PartNoId PartNo-001A description QtyOrd 20'


PartNoId

PartNoId PartNo-001A description QtyOrd 20'

 
PartNoId PartNoId PartNo-001A description QtyOrd 20 some other description
PartNoId PartNoId PartNo-002A description QtyOrd 20 some other description 

 
PartNoId PartNo-001A description QtyOrd 20 some other description
PartNoId PartNo-002A description QtyOrd 20 some other description 

如何解决此问题。

【问题讨论】:

    标签: python regex regex-lookarounds regex-group regexp-replace


    【解决方案1】:

    在替换之前只需添加一个if 语句来检查PartNoId 是否为in 字符串。

    def process_PartNo(text):
        if 'PartNoId' not in text:
            text = re.sub(r'(PartNo-)', r'PartNoId \1', text, flags=re.IGNORECASE|re.DOTALL)
            return text
        return text
    

    如果PartNoId 不存在于字符串中,这只会运行re.sub()

    【讨论】:

    • 非常感谢您的解决方案
    【解决方案2】:

    您可以选择将PartNoId 与后面的空格匹配,就在PartNo- 之前:

    def process_PartNo(text):    
        return re.sub(r'(?:PartNoId\s+)?(PartNo-)', r'PartNoId \1', text, flags=re.I)
    

    请参阅 Python demoregex demo。添加单词边界,\b,如果您只需要匹配整个单词,r'\b(?:PartNoId\s+)?(PartNo-)'

    详情

    • \b - 单词边界
    • (?:PartNoId\s+)? - 一个可选的非捕获组,匹配一次或零次出现的 PartNoId,然后是一个或多个空格
    • (PartNo-) - 第 1 组:PartNo- 文字。

    【讨论】:

    • 非常感谢您的解决方案
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多