Search code examples
regexregex-lookarounds

Regex to match strings only if in combination


i need to match and replace the text in the following ways

if the text is as below, it should not be replaced

home travel or home visit or home flight - then don't replace

if the text is as below it should be replaced

travel or visit or flight - replace

I have tried

(?!(home|parents))(?=(flight|visit|travel))

How can match it in such a way?


Solution

  • If there is a single space, you can use a 2 negative lookbehinds instead of a lookahead.

    (?<!\bhome )(?<!\bparents )\b(?:flight|visit|travel)\b
    

    Regex demo

    If there can be multiple whitespace chars, you can capture the pattern that you want to keep, and use that in the replacement. What you want to replace, you can match (so not capture in a group)

    For example using Python:

    import re
    
    strings = [
        "home   travel or home   visit or home    flight",
        "travel or visit or flight"
    ]
    pattern = r"\b((?:home|parents)\s+(?:flight|visit|travel))\b|\b(?:flight|visit|travel)\b"
    for s in strings:
        print(
            re.sub(
                pattern,
                lambda x: x.group(1) if x.group(1) else "[replacement here]",
                s
            )
        )
    

    Output

    home   travel or home   visit or home    flight
    [replacement here] or [replacement here] or [replacement here]
    

    Python demo