簡體   English   中英

如何在javascript中匹配包含動態組件的字符串

[英]How to match a string contain dynamic components in javascript

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

明天的天氣將是太陽而不是雲。 上部80的高點和30中的低點。明天的天氣將是太陽而不是雲。 40年代中期的高點和70年代的低點。 明天的天氣將是太陽而不是雲。 在80年代的低點和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");
            }

但是我總是得到“不匹配”的回應

首先, {...|...}沒有定義一組備選方案, {}是文字符號。 您需要捕獲(...)或非捕獲組(?:...) 然后,您不能只使用正則表達式對象連接字符串,在事先知道模式的情況下使用正則表達式文字。 模式內的錨點會立即失敗,因為它們表示字符串開始/結束( ^ / $ )。

此外, high|low|mid替代品不允許在您需要匹配的第一個字符串中存在的upper 數字后面的s並不總是強制性的,添加? 量化后。 組之間的空格和模式中的文字文本是必需的,否則模式將不匹配。

應該轉義正則表達式模式中的文字點,否則它匹配任何字符,但匹配換行符號。

我建議:

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?\./

請參閱正則表達式演示

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

另一種方法,只需刪除那些改變的單詞然后進行比較。 如果任何其他單詞出現在上|高|中|的位置將沒有問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM