I would like to imitate conditional expressions in javascript regex

This is what I still have ...

var regex_string = "s(at)?u(?(1)r|n)day"
console.log("Before: "+regex_string)
var regex_string = regex_string.replace(/\(\?\((\d)\)(.+?\|)(.+?)\)/g,'((?!\\$1)$2\\$1$3)')
console.log("After: "+regex_string)
var rex = new RegExp(regex_string)

var arr = "thursday tuesday thuesday tursday saturday sunday surday satunday monday".split(" ")
for(i in arr){
  var m
  if(m = arr[i].match(rex)){
    console.log(m[0])
  }
}

I replace (?(n)a|b)for ((?!\n)a|\nb), where nis the number, and aand bare the strings. This seems to work fine, but I know this is a big fat hack.

Is there a better way to approach this problem?

+5
source share
1 answer

In the specific case of your regular expression, it is much easier and more readable to use interleaving:

(?:sunday|saturday)

, ( , , ). , un atur, , :

s(?:un|atur)day

2 . ( , Perl, , JavaScript ).

  • - , . JavaScript regex. , , :

    (?(conditional-pattern)yes-pattern|no-pattern)
    

    JavaScript , () , conditional-pattern :

    ((?=conditional-pattern)yes-pattern|(?!conditional-pattern)no-pattern)
    

    , , conditional-pattern yes-pattern, no-pattern. , .

  • - ( ), true, . .

    , , - , , . , , . , ( RegExp), source, ; , / .

+12

All Articles