在 Python 中使用正则表达式在 PartNo 之前添加 PartNoId 标识符- [英] Using Regex in Python to add PartNoId identifier before PartNo-

查看:42
本文介绍了在 Python 中使用正则表达式在 PartNo 之前添加 PartNoId 标识符-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Regex in Python to add PartNoId identifiers before PartNo-.

我使用的代码如下:

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

But in case of ample text where already PartNoId already exits there should not be added again 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 

如何解决这个问题.

推荐答案

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

Simply add an if statement to check if PartNoId is in the string prior to replacing.

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

This will only run the re.sub() if PartNoId does not exist in the string already.

这篇关于在 Python 中使用正则表达式在 PartNo 之前添加 PartNoId 标识符-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆