Regex - check if input still has chances to become matching

前端 未结 11 1472
天命终不由人
天命终不由人 2020-12-05 00:51

We\'ve got such regexp:

var regexp = /^one (two)+ three/;

So only string like \"one two three\" or \"one two three four\

11条回答
  •  情书的邮戳
    2020-12-05 01:16

    I think there is no automatic "Apply to every Pattern"-Solution. However you can manually derive an "optional" pattern out of your regex, and check against both patterns:

    var fullPattern = /^one (two)+ three/;
    var optPattern = /^o?n?e? ?(t?w?o?)+ ?t?h?r?e?e?$/;
    
    //verbal
    if (fullPattern.matches()){
       //matched
    } else {
      if (optPattern.matches()){
         //looks promising
      }else{
         //no match.
      }
    }
    

    You could also implement your own optionalizePattern() method, that converts Regex Pattern into such an Optional derivate. (Will be a difficult task to cover ALL possible patterns. Dunno, if possible at all.)

提交回复
热议问题