简体   繁体   中英

JavaScript: combine two regular expressions to satisfy both?

How can multiple regular expressions be combined to satisfy both conditions?

Below, there are 3 strings and 2 regular expressions:

  • The first Regex doesn't allow a string to start with a dollar sign.
  • The second Regex doesn't allow the string to have periods.

How can these two regular expressions be combined so that strings don't start with a dollar sign and have periods be considered a match?

 var good_string = "flkad sdfa$af fjf"; var bad_string_1 = "$flkadjf"; var bad_string_2 = "flk.adjf"; var does_not_contain_periods = new RegExp('^[^.]*$'); var does_not_start_with_dollar_sign = new RegExp('^(?!\\\\$)'); var combined_regular_expressions = new RegExp("(" + does_not_contain_periods.source + ")(" + does_not_start_with_dollar_sign.source + ")"); console.log('--- does_not_contain_periods ---') console.log(good_string.match(does_not_contain_periods)); console.log(bad_string_1.match(does_not_contain_periods)); console.log(bad_string_2.match(does_not_contain_periods)); console.log('--- does_not_start_with_dollar_sign ---') console.log(good_string.match(does_not_start_with_dollar_sign)); console.log(bad_string_1.match(does_not_start_with_dollar_sign)); console.log(bad_string_2.match(does_not_start_with_dollar_sign)); console.log('--- combined_regular_expressions ---') console.log(good_string.match(combined_regular_expressions)); console.log(bad_string_1.match(combined_regular_expressions)); console.log(bad_string_2.match(combined_regular_expressions)); console.log('--- desired result ---') console.log(good_string.match(does_not_contain_periods) !== null && good_string.match(does_not_start_with_dollar_sign) !== null); console.log(bad_string_1.match(does_not_contain_periods) !== null && bad_string_1.match(does_not_start_with_dollar_sign) !== null); console.log(bad_string_2.match(does_not_contain_periods) !== null && bad_string_2.match(does_not_start_with_dollar_sign) !== null); 

RegExps cannot be easily combined that way.

You better just test (matching makes no sense in this case) all of them.

function testAll(regexps, ...args) {
  return regexps.every(regexp => regexp.test(...args));
}

var good_string = "flkad sdfa$a f fjf";
var bad_string_1 = "$flkadjf";
var bad_string_2 = "flk.adjf";

console.log(testAll([/^[^.]*$/, /^(?!\$)/], good_string));
console.log(testAll([/^[^.]*$/, /^(?!\$)/], bad_string_1));
console.log(testAll([/^[^.]*$/, /^(?!\$)/], bad_string_2));

您可以通过使用OR metaChar“ |”来使用一个RegX进行测试

var regX = /^\$|\./;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM