Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a string contain dynamic components in javascript

below are the strings I have to match

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

I tried below:

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

however I always get "not matched" response

like image 466
ewanthak Avatar asked Jul 11 '26 17:07

ewanthak


1 Answers

First of all, the {...|...} does not define a group of alternatives, the { and } are literal symbols. You need either capturing (...) or non-capturing groups (?:...). Then, you cannot just concatenate strings with regex objects, use the regex literal in case the pattern is known beforehand. The anchors inside the pattern fail the pattern right away since they denote string start/end (^ / $).

Also, high|low|mid alternatives do not allow upper that is present in the first string you need to match. The s after number is not always compulsory, add ? quantifier after it. Spaces between the groups and literal text in the pattern are necessary, or the pattern will not match.

A literal dot inside the regex pattern should be escaped, else it matches any char but a linebreak symbol.

I'd suggest:

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

See the 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");
  }
 }
like image 70
Wiktor Stribiżew Avatar answered Jul 13 '26 08:07

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!