Regular expression for numbers with one space in undefined positions

Am I trying to write a regex to test single-space numbers in undefined places?

Maximum 12 characters with one space or Maximum 11 characters without spaces.

Example: '25897 569874', '5674', '65783987665', '435 6523'

I tried with ^[0-9]{0,12}$ . This is not an ideal reason, I do not know how to place spaces and their score.

0
source share
2 answers

You can use this regex:

 ^(?:\d{1,11}|(?=\d+ \d+$)[\d ]{3,12})$ 

\d{1,11} will match 1 to 11 digits without a space.

(?=\d+ \d+$)[\d ]{3,12} will correspond to 11 digits with one space somewhere in the middle. The space cannot be trailing or trailing, so ' 23' will be rejected.

  • (?=\d+ \d+$) is a forecast that matches one or more digits, then a space, then one or more digits, and then anchors the end of the line. It ensures that only one space appears and that the space does not move forward or backward. A look ahead also implicitly confirms that the line contains at least 3 characters.
  • [\d ]{3,12} ensures that the string contains only numbers or a space and up to 12 of them. The lower bound on the number of repetitions can be set to 3 or lower, as this is implied by appearance.

2 restrictions together guarantee that the text contains from 1 to 11 digits and an optional space in an arbitrary position between the digits.


To allow a leading space but reject one space, an empty string and trailing spaces:

 ^(?:\d{1,11}|(?=\d* \d+$)[\d ]{2,12})$ 

Again, standby means at least 2 characters, so the number of repetitions can be set to 2 or lower.

+4
source

^ [0-9] {0.12} $ will correspond to 12 character lines with or without space. If you need some criteria, try the OR (pipe) operator: |

^ [0-9] {0.12} $ | another condition

-1
source

All Articles