2016-10-21 79 views
3

下面是我必須匹配的字符串如何匹配字符串中包含javascript的動態組件

明天的天氣將比雲更多。 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"); 
      } 

但是我總是「不匹配」的響應

+0

難道你不能把模式寫成單一模式嗎? ['var regEx = /明天的天氣將比雲彩更加陽光\。 (上|高|低] [0-9] {2}?的高點?並且在(high | low | mid)[0-9] {2} s?\ ./;'](https://regex101.com/r/vHwkJR/1)中處於低位您是否需要使用正則表達式連接字符串對象源模式?請注意,您必須匹配單詞之間的空格,並使's'成爲可選項,因爲它不在任何地方,並且其中一個組不包含'upper'值。 –

+0

謝謝你這是工作 – ewanthak

回答

1

首先,在{...|...}沒有定義一組的替代品,{}是文字符號。您需要捕獲(...)或非捕獲組(?:...)。然後,您不能只將字符串與正則表達式對象連接起來,如果事先知道該模式,請使用正則表達式。由於它們表示字符串開始/結束(^/$),圖案內的錨點會立即失敗。

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

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

+0

很高興爲你工作。請考慮接受答案(請參閱[如何接受SO答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)),並且如果我的答案證明對我有幫助,你(見[如何在堆棧溢出?](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow))。 –

0

的另一種方法,就消除這些改變的話,然後進行比較。 如果有任何其他字來代替上面的|高的|低的|中間的將是沒有問題的。

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"); 
} 
相關問題