How to create a regex pattern equal to 1,2,3

Viewed 444

Currently, on the project, they have a pattern [^0-9,] and it replaces (String.prototype.replace) everything that we don't need. Except it's not so great. We can add a comma to the start and to the end of the string.

What do I need and I can't do it no matter how hard I try)

  1. first should be a number in the range 0-9
  2. after the first number should be a comma (one comma) or a number or numbers (0-9)
  3. at the end of the line shouldn't be a comma

Correct example,

1,2,3

Incorrect,

,,,,1,,2dgd,d,
1,2,3,
,1,2,,,3

UPD: The method String.prototype.replace() is used on the project.

I'll be grateful if you help me!

2 Answers

If the comma's are optional, maybe you need:

^\d+(?:,\d+)*$

See the online demo


  • ^ - Start string ancor
  • \d+ - One or more digits.
  • (?:- Open non-capture group.
    • ,\d+ - A comma followed but one or more digits.
    • )* - Close non-capture group and match zero or more times.
  • $ - End string ancor.

Edit:

If you actually want to clean a string, maybe you could use:

(\d+).*?(,(?=.*\d))|\D

See the online demo. Just make sure to replace by $1$2.


  • (\d+) - 1st Capture group with one or more digits.
  • .*? - Lazy match anything opto:
  • (,(?=.*\d)) - 2nd Capture group to match literal comma with a nested positive lookahead to ensure there is still a digit ahead.
  • | - Or:
  • \D - Anything other than digit.

const regexp = new RegExp(/(\d+).*?(,(?=.*\d))|\D/g);      
const value = '1,2,3'.replace(regexp, '$1$2');
console.log(value)

This should work:

^[0-9]+(?:,[0-9]+)*$

Begins with a digit or a set of digits, followed by zero or more occurrences of a comma followed by one or more digits. Don't miss the start and end line anchors. Demo

Related