下面是我必须匹配的字符串
明天的天气将是晴天而不是多云。最高的80度,最低的30度。明天的天气将是晴天而不是多云。最高点在40华氏度左右,最低点在70华氏度。明天的天气将是晴天而不是多云。最高50华氏度,最低80华氏度
我试过以下几种方法:
var str = "The weather tomorrow will be more sun than clouds. Highs in the low 50s and lows in the high 80s";
var regEx = new RegExp("The weather tomorrow will be more sun than clouds. Highs in the "+/{high|low|mid}$/+/^[0-9]{2}$/+"s and lows in the "+/{high|low|mid}$/+/^[0-9]{2}$/+"s.");
if(str.match(regEx)){
console.log("matched");
}else{
console.log("not matched");
}
但是,我总是得到“不匹配”的响应
发布于 2016-10-21 19:18:43
首先,{...|...}
没有定义一组备选方案,{
和}
都是文字符号。您需要捕获(...)
或非捕获组(?:...)
。然后,您不能仅将字符串与regex对象连接在一起,在模式事先已知的情况下使用regex文本。模式中的锚点立即使模式失效,因为它们表示字符串开始/结束(^
/ $
)。
此外,high|low|mid
替代方案不允许出现在您需要匹配的第一个字符串中的upper
。number后面的s
并不总是必填的,请在它后面添加?
限定符。组和模式中的文字文本之间必须有空格,否则模式将不匹配。
regex模式中的一个文字点应该被转义,否则它将匹配除换行符以外的任何字符。
我建议:
var regEx = /The weather tomorrow will be more sun than clouds\. Highs in the (upper|high|low|mid) [0-9]{2}s? and lows in the (high|low|mid) [0-9]{2}s?\./
请参阅regex demo
var strs = ["The weather tomorrow will be more sun than clouds. Highs in the upper 80 and lows in the mid 30.", "The weather tomorrow will be more sun than clouds. Highs in the mid 40s and lows in the high 70s.", "The weather tomorrow will be more sun than clouds. Highs in the low 50s and lows in the high 80s."];
var regEx = /The weather tomorrow will be more sun than clouds\. Highs in the (upper|high|low|mid) [0-9]{2}s? and lows in the (high|low|mid) [0-9]{2}s?\./;
for (var str of strs) {
if(str.match(regEx)){
console.log("matched");
} else {
console.log("not matched");
}
}
发布于 2016-10-21 19:47:47
另一种方法,只需删除那些变化的单词,然后进行比较。如果任何其他单词出现在be |high|low|mid的位置,将不会有任何问题。
my_str = "The weather tomorrow will be more sun than clouds. Highs in the and lows in the";
given_str = "The weather tomorrow will be more sun than clouds. Highs in the upper 80 and lows in the mid 30.";
var res = given_str.split(" ");
rem_arr = [12,13,18,19];
for (var i = rem_arr.length -1; i >= 0; i--) {
res.splice(rem_arr[i],1);
}
if(my_str.localeCompare(res.join(' ')) == 0) {
console.log("matched");
} else {
console.log("not matched");
}
https://stackoverflow.com/questions/40174776
复制相似问题