JavaScript:组合两个正则表达式来满足两者?



如何组合多个正则表达式以满足这两个条件?

下面,有 3 个字符串和 2 个正则表达式:

  • 第一个正则表达式不允许字符串以美元符号开头。
  • 第二个正则表达式不允许字符串具有句点。

如何将这两个正则表达式组合在一起,以便字符串不以美元符号开头,并且将句点视为匹配项?

var good_string = "flkad sdfa$a f 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 不能以这种方式轻松组合。

您最好只测试(在这种情况下匹配没有意义(所有这些。

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));

您可以使用一个 RegX 通过使用 OR 元字符"|"来测试两者

var regX = /^$|./;

最新更新