In a regular expression, match one thing or another, or both

前端 未结 5 1407
悲哀的现实
悲哀的现实 2020-11-28 14:35

In a regular expression, I need to know how to match one thing or another, or both (in order). But at least one of the things needs to be there.

For example, the fol

5条回答
  •  伪装坚强ぢ
    2020-11-28 14:46

    The fully general method, given regexes /^A$/ and /^B$/ is:

    /^(A|B|AB)$/
    

    i.e.

    /^([0-9]+|\.[0-9]+|[0-9]+\.[0-9]+)$/
    

    Note the others have used the structure of your example to make a simplification. Specifically, they (implicitly) factorised it, to pull out the common [0-9]* and [0-9]+ factors on the left and right.

    The working for this is:

    • all the elements of the alternation end in [0-9]+, so pull that out: /^(|\.|[0-9]+\.)[0-9]+$/
    • Now we have the possibility of the empty string in the alternation, so rewrite it using ? (i.e. use the equivalence (|a|b) = (a|b)?): /^(\.|[0-9]+\.)?[0-9]+$/
    • Again, an alternation with a common suffix (\. this time): /^((|[0-9]+)\.)?[0-9]+$/
    • the pattern (|a+) is the same as a*, so, finally: /^([0-9]*\.)?[0-9]+$/

提交回复
热议问题