Home > database >  Regex for list number and allow empty space
Regex for list number and allow empty space

Time:06-18

The sample i wanna past through the regex is with follow requirement

  1. list of number seperate by comma
  2. at least input 10 number in list
  3. only accept numbers but could allow empty space in both front and back Here is my sample regex code:
^(?:(\-|\ |)\d (?:\.\d*)?|(\-|\ |)\.\d ) (?:,(?:(\-|\ |)\d (?:\.\d*)?|(\-|\ |)\.\d )){9,}$  

This regex test code could pass list number seperate by comma,
however when i add empty space in front and on the back it will not work
The following testing Code is failed

'  2,2.5,.5,  .678   ,39,1.4.4.8,2.4,2.5,2.6,2.7'

CodePudding user response:

You might use

^\s*[ -]?\d*\.?\d (?:\.\d )*(?:\s*,\s*[ -]?\d*\.?\d (?:\.\d )*){9,}\s*$

The pattern matches:

  • ^ Start of string
  • \s*[ -]?\d*\.?\d Match an optional plus or minus sign, optional digits and optional dot followed by 1 or more digits
  • (?:\.\d )* As there are digits with multiple dot parts, you can optionally repeat that
  • (?:\s*,\s*[ -]?\d*\.?\d (?:\.\d )*){9,} That first part of the pattern matches 1 time. As you want to match at least 10 times you can repeat the first pattern 9 or more times, starting with a comma between optional whitespace chars
  • \s*$ Optional trailing whitespace chars and assert end of string

Regex demo

Note that \s can also match a newline.

If you don't want that, you could use for example a mere space or [ \t]

  • Related