如何组合多个正则表达式以满足两个条件?
下面有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);
答案 0 :(得分:0)
RegExps无法以这种方式轻松组合。
您最好只测试所有(在这种情况下,匹配没有意义)。
...
imports: [SharedModule]
...
答案 1 :(得分:0)
通过使用OR metaChar“ |”
,您可以只使用一个RegX来测试两者var regX = /^\$|\./;