Using explicitly numbered repetition instead of question mark, star and plus

后端 未结 4 2137
谎友^
谎友^ 2020-11-21 11:00

I\'ve seen regex patterns that use explicitly numbered repetition instead of ?, * and +, i.e.:

Explicit            Sho         


        
4条回答
  •  面向向阳花
    2020-11-21 11:53

    I can see how, if you have a regex that does a lot of bounded repetition, you might want to use the {n,m} form consistently for readability's sake. For example:

    /^
     abc{2,5}
     xyz{0,1}
     foo{3,12}
     bar{1,}
     $/x
    

    But I can't recall ever seeing such a case in real life. When I see {0,1}, {0,} or {1,} being used in a question, it's virtually always being done out of ignorance. And in the process of answering such a question, we should also suggest that they use the ?, * or + instead.

    And of course, {1} is pure clutter. Some people seem to have a vague notion that it means "one and only one"--after all, it must mean something, right? Why would such a pathologically terse language support a construct that takes up a whole three characters and does nothing at all? Its only legitimate use that I know of is to isolate a backreference that's followed by a literal digit (e.g. \1{1}0), but there are other ways to do that.

提交回复
热议问题