Regex to match a digit two or four times

后端 未结 2 718
日久生厌
日久生厌 2020-12-12 21:45

It\'s a simple question about regular expressions, but I\'m not finding the answer.

I want to determine whether a number appears in sequence exactly two

相关标签:
2条回答
  • 2020-12-12 22:05

    There's no specific syntax for that, but there are lots of ways to do it:

    (?:\d{4}|\d{2})    <-- alternation: four digits if possible, else just two
    \d{2}(?:\d{2})?    <-- two digits, plus two more if possible
    (?:\d{2}){1,2}     <-- two digits, times one or two
    

    So, for example, to match strings consisting of one or more letters A–Z followed by either two or four digits, you might write ^[A-Z]+(?:\d{4}|\d{2})$; and to match a comma-separated list of two-or-four-digit numbers, you might write ^((?:\d{4},|\d{2},)*(?:\d{4}|\d{2})$ or ^(?:\d{2}(?:\d{2})?,)*\d{2}(?:\d{2})$.

    0 讨论(0)
  • 2020-12-12 22:17
    (?<!\d)(\d{2}|\d{4})(?!\d)
    

    This is the correct way to do it. The accepted answer is wrong.

    It would match 3 digits (or 5). So that is wrong in my eyes.

    1) Check there is no digit before a sequence of 2, or 4 digits, or after a sequence of two or four digits.

    • (<!) syntax is negative lookbehind

    • (?!) syntax is negative lookahead.

    The above would work for mid string:

    If your search string has no content around it you could use the ^ and $ start and end of string anchors:

    ^\d{4}$|^\d{2}$
    
    0 讨论(0)
提交回复
热议问题