How to handle something like [1,2,3] with html5 input type text?

Viewed 43

I would like to know if we can handle specific input like the following examples using pattern:

[1] or [1,2]

so basically brackets with a number or if there are more numbers then only comma allowed as a separator.

Tried [(\d+(\s*,?))+] as stated below but it doesn't work.

2 Answers

This would do it:

^\[(?:\d+(?:,\d+)*)?\]$
  • ^ - start line anchor
  • \[ - open literal square bracket
  • (?: - open non-capturing group
    • \d+ - one or more digits
    • (?: - open non-capturing group
      • ,\d+ - comma followed by one or more digits
    • ) - close non-capturing group
    • * - match pattern inside non-capturing group zero or more times
  • ) - close non-capturing group
  • ? - make the preceding non-capturing group content optional; basically, allow for empty []
  • \] - close literal square bracket
  • $ - end line anchor

https://regex101.com/r/BuRsND/1

Use this regex \[(\d+(\s*(,(?=\d))?))+\]

Related