【发布时间】: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