Search code examples
regexdefault

Regex default value if not found


I would like to supply my regular expression with a 'default' value, so if the thing I was looking for is not found, it will return the default value as if it had found it.

Is this possible to do using regex?


Solution

  • It sounds like you want some sort of regex syntax that says "if the regexp does not match any part of the given string pretend that it matched the following substring: 'foobar'". Such a feature does not exist in any regexp syntax I've seen.

    You'll probably need to something like this:

    matched_string = string.find_regex_match(regex);
    if(matched_string == null) {
      string = "default";
    }
    

    (This will of course need to be adjusted to the language you're using)