Home > Mobile >  Regex to allow groups of 7 numbers and spaces
Regex to allow groups of 7 numbers and spaces

Time:09-10

I'm looking for help with a regex.

My input field should allow only groups of up to 7 digits, and an unlimited number spaces whether at the beginning, middle, or end.

Here are a few examples of valid matches

Match1:
478 2635478     14587   9652

Match2 (spaces at the end):
   14     2  55586  

I tried this regex

^( )*[0-9]{1,7}(( )*[0-9]{1-7})*( )*$

It matches when the group is 8 digits.

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex:

^ *[0-9]{1,7}(?:  [0-9]{1,7})* *$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • *: Match 0 or more spaces
  • [0-9]{1,7}: Match 1 to 7 digits -(?: [0-9]{1,7})*: Match 1 spaces followed by a match of 1 to 7 digits. Repeat this group 0 or more times
  • *: Match 0 or more spaces
  • $: End

CodePudding user response:

An idea with one group and use of a word boundary to separate blocks:

^ *(?:\d{1,7}\b *) $

See this demo at regex101 (more explanation on the right side)

\b will require a space or the end after each \d{1,7} repetition.

  • Related