JavaScript:结合使用两个正则表达式来满足这两个条件?

时间:2018-08-09 15:21:55

标签: javascript regex

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

下面有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);

2 个答案:

答案 0 :(得分:0)

RegExps无法以这种方式轻松组合。

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

...
imports: [SharedModule]
...

答案 1 :(得分:0)

通过使用OR metaChar“ |”

,您可以只使用一个RegX来测试两者
var regX = /^\$|\./;