Milan Vrškový
Milan Vrškový

Reputation: 13

REGEX - Limit only numbers in a string, but allow any number of other specific characters

I currently have this: ^\+?[()\d -]{6,12}

It allows a leading +, allows ()- characters, and numbers. But the total length of the string is limited to 6-12 characters.

I want to achieve the following:

valid:

123456  
+123456  
+(12) (2)3-5-2

invalid:

1234  
1 2 (3) 4  
1233451231231 

Upvotes: 1

Views: 601

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex,

^\+?(?:[()\h-]*\d[()\h-]*){6,12}$

Demo

Explanation:

  • ^ - Start of string
  • \+? - Matches optional plus character
  • (?:[()\h-]*\d[()\h-]*) - This basically matches zero or more your non-digits allowed characters followed by a single digit then again followed by zero or more your non-digits allowed characters
  • {6,12} allows above text minimum six and maximum 12 times
  • $ - End of string

You haven't mentioned regex dialect, hence if \h (horizontal space) is not supported, then you can use normal space or use \s

Upvotes: 1

Related Questions