14

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?

Zim
  • 5,403
  • 7
  • 27
  • 19
  • https://stackoverflow.com/a/38579881 shows how to return an empty string as "default" value (in Python) – djvg Sep 24 '20 at 10:42
  • Similar to this, I've only been able to come up with having empty strings returned as default aka `(your regex|.{0})` – Dmytro Bugayev Mar 21 '23 at 18:04

4 Answers4

4

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)

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

As far as I know, you can't do that with RegExp`s, at least with Perl Compatible Regular Expressions.

You can see by your self here.

Cleiton
  • 17,663
  • 13
  • 46
  • 59
1

It's hard to answer this without a specific language, but in Perl at least, something like this works:

$string='hello';
$default = 1234;
($match) = ($string =~ m/(\d+)/ or $default);
print "$match\n";

1234

Not strictly part of the regex, but avoids the extra conditional block.

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
0

Here's what I did in javascript...

function match(regx, str, dflt, index = 0) {
    if (!str) return dflt
    let x = str.match(regx)
    return x ? x[index] || dflt : dflt
}
chad steele
  • 828
  • 9
  • 13