Regex default value if not found

妖精的绣舞 提交于 2020-05-08 06:39:08

问题


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?


回答1:


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)




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1320456/regex-default-value-if-not-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!