Regex - check if input still has chances to become matching

前端 未结 11 1402
天命终不由人
天命终不由人 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:04

    Another interesting option that I have used before is to OR every character expected with the $ symbol. This may not work well for every case but for cases where you are looking at specific characters and need a partial match on each character, this works.

    For example (in Javascript):

    var reg = /^(o|$)(n|$)(e|$)(\s|$)$/;
    
    reg.test('')      -> true;
    reg.test('o')     -> true;
    reg.test('on')    -> true;
    reg.test('one')   -> true;
    reg.test('one ')  -> true;
    reg.test('one t') -> false;
    reg.test('x')     -> false;
    reg.test('n')     -> false;
    reg.test('e')     -> false;
    reg.test(' ')     -> false;
    

    While this isn't the prettiest regex, it is repeatable so if you need to generate it dynamically for some reason, you know the general pattern.

    The same pattern can be applied to whole words as well, which probably isn't as helpful because they couldn't type one-by-one to get to these points.

    var reg = /^(one|$)(\stwo|$)$/;
    
    reg.test('')        -> true;
    reg.test('one')     -> true;
    reg.test('one ')    -> false;
    reg.test('one two') -> true;
    

提交回复
热议问题