regexstringcharacter

Regex: Select everything before particular character and other substring, or select everything if neither substring nor character exist


I need a single regex expression that can select everything before a : character, and/or everything before the substring Hello. If neither : or Hello are in the string, I need to select everything.

Examples and Expected Output:

So far, I've found this expression, (^[^:]+), which will return everything before a ":" character.


Solution

  • This regex should do what you want. It looks for a minimal number of characters to capture (.*?) followed by either :, Hello or the end of line ($):

    ^(.*?)(?=:|Hello|$)
    

    Demo on regex101

    This will work if you are testing one value at a time and don't use the g flag. Otherwise the string "Hello" will match twice, once with the empty string at the beginning of the line, and once with Hello. If that is an issue, you can use this regex which prevents that from happening while still capturing values such as "Howdy":

    ^(?:.*?)(?=Hello|:)|^(?!.*(Hello|:)).*$
    

    Demo on regex101