How to detect exact length in regex

前端 未结 8 490
青春惊慌失措
青春惊慌失措 2020-12-11 02:42

I have two regular expressions that validate the values entered.

One that allows any length of Alpha-Numeric value:

@\"^\\s*(?[A-Z0-9]+)         


        
相关标签:
8条回答
  • 2020-12-11 03:03

    I think what you're trying to say is that you don't want to allow any more than 10 digits. So, just add a $ at the end to specify the end of the regex.

    Example: @"^\s*(?[0-9]{10})$"


    Here's my original answer, but I think I read you too exact.

    string myRegexString = `@"(?!(^\d{11}$)` ... your regex here ... )";
    

    That reads "while ahead is not, start, 11 digits, end"

    0 讨论(0)
  • 2020-12-11 03:04

    If it's single line, you could specify that your match must happen at the end of the line, like this in .net ...

    ^\s*([0-9]{10})\z
    

    That will accept 1234567890 but reject 12345678901.

    0 讨论(0)
  • 2020-12-11 03:05

    If you are trying to match only numbers that are 10 digits long, just add a trailing anchor using $, like this:

    ^\s*(?:[0-9]{10})\s*$
    

    That will match any number that is exactly 10 digits long (with optional space on either side).

    0 讨论(0)
  • 2020-12-11 03:05

    This should match only 10 digits and allow arbitrary numbers of whitespaces before and after the digits.

    Non-capturing version: (only matches, the matched digits are not stored)

    ^\s*(?:\d{10})\s*$
    

    Capturing version: (the matched digits are available in subgroup 1, as $1 or \1)

    ^\s*(\d{10})\s*$
    
    0 讨论(0)
  • 2020-12-11 03:06

    var pattern =/\b[0-9]{10}$\b/;
    
    // the b modifier is used for boundary and $ is used for exact length

    0 讨论(0)
  • 2020-12-11 03:10

    You could try alternation?

    ^\s*(?\d{1,10}|\d{12,})
    
    0 讨论(0)
提交回复
热议问题