Skip to content Skip to sidebar Skip to footer

Using Regex In Python To Add PartNoId Identifier Before PartNo-

I am using Regex in Python to add PartNoId identifiers before PartNo-. The Code am using is below: import re def process_PartNo(text): text = re.sub(r'(PartNo-)', r'PartNoI

Solution 1:

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

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


Solution 2:

You can optionally match PartNoId with whitespace after it, right before PartNo-:

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

See the Python demo and the regex demo. Add word boundaries, \b, if you need to match whole words only, r'\b(?:PartNoId\s+)?(PartNo-)'.

Details:

  • \b - a word boundary
  • (?:PartNoId\s+)? - an optional non-capturing group matching one or zero occurrences of PartNoId and then one or more whitespaces
  • (PartNo-) - Group 1: PartNo- text.

Post a Comment for "Using Regex In Python To Add PartNoId Identifier Before PartNo-"