0

I want to know if a string is a collection of, by example, numbers ([0-9]).

I this case, i'm using the regular expression [0-9](,[0-9])* to find one or more numbers separated by commas (A collection of numbers).

Is there a better way to do it? I mean a shorter expression perhaps.

André Kuljis
  • 90
  • 1
  • 9
  • Impossible to say without a sample of the data - but if your data that need to be matched is single digits separate only by commas, only `\d(,\d)*` is a bit briefer – Grismar Sep 18 '20 at 02:39
  • 1
    take a look at this [answer](https://stackoverflow.com/questions/1396084/regex-for-comma-delimited-list) in which the top rated answer describes a regex pattern for extracting elements from a CSV. – Taylr Cawte Sep 18 '20 at 02:39

2 Answers2

1

I would suggest the following pattern:

(?<=^|,|\s)(\d+)

(?<=...) is a lookbehind assertion that will not be captured into the groups nor be included into the matched string. It is used to identify the starting position of the number to be matched.

You can try the above pattern interactively in the following website:

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

Ken T
  • 2,255
  • 1
  • 23
  • 30
0

\d*(,\d*)* will catch the situation where you have multiple digits before and after a comma e.g. 100,000. This regex will only grab 0,0 from that same number.

jrmylow
  • 679
  • 2
  • 15
  • Should be `\d+` instead of `\d*` to ensure at least one digit. Using `*` will match "empty numbers" as in ``1,2,,,,3``. – fmigneault Sep 18 '20 at 04:44