Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • The length limit only applies to the numeric characters. Any number of the other special characters is allowed

valid:

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

invalid:

1234
1 2 (3) 4
1233451231231

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading