首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在javascript中匹配包含动态组件字符串

如何在javascript中匹配包含动态组件字符串
EN

Stack Overflow用户
提问于 2016-10-21 18:52:57
回答 2查看 68关注 0票数 3

下面是我必须匹配的字符串

明天的天气将是晴天而不是多云。最高的80度,最低的30度。明天的天气将是晴天而不是多云。最高点在40华氏度左右,最低点在70华氏度。明天的天气将是晴天而不是多云。最高50华氏度,最低80华氏度

我试过以下几种方法:

代码语言:javascript
运行
复制
            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");
            }

但是,我总是得到“不匹配”的响应

EN

回答 2

Stack Overflow用户

发布于 2016-10-21 19:18:43

首先,{...|...}没有定义一组备选方案,{}都是文字符号。您需要捕获(...)或非捕获组(?:...)。然后,您不能仅将字符串与regex对象连接在一起,在模式事先已知的情况下使用regex文本。模式中的锚点立即使模式失效,因为它们表示字符串开始/结束(^ / $)。

此外,high|low|mid替代方案不允许出现在您需要匹配的第一个字符串中的upper。number后面的s并不总是必填的,请在它后面添加?限定符。组和模式中的文字文本之间必须有空格,否则模式将不匹配。

regex模式中的一个文字点应该被转义,否则它将匹配除换行符以外的任何字符。

我建议:

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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");
  }
 }

票数 1
EN

Stack Overflow用户

发布于 2016-10-21 19:47:47

另一种方法,只需删除那些变化的单词,然后进行比较。如果任何其他单词出现在be |high|low|mid的位置,将不会有任何问题。

代码语言:javascript
运行
复制
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");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40174776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档