Given a string such as:
23,234,456 first second third
How can I split string this into two parts, where part 1 contains the number at the beginning and part 2 contains the rest—but only if the string STARTS with a number, and the number can be comma-separated or not? In other words, I want two results: 23,234,456 and first second third. If there’s a number in that string that isn’t part of the first number then it should be in the second result.
My best stab at this so far, to grab the number at the beginning, is something like this:
^[0-9]+(,[0-9]{3})*
Which seems to grab a comma-separated or non-comma-separated number that starts the line. However, when I run this in the Javascript console I get not only the full number, but also a match on just the last 3 digits with their preceeding ,. (e.g. 23,234,456 and ,456).
As for getting the rest into another var I’m having trouble. I tried working with \b, etc., but I think I must be missing something fundamental about grabbing the rest of the line.
I’m doing this in Javascript in case it matters.
More examples of what to match and what not to match.
2 one two three should return 2 and one two three
2345 one two three should return 2345 and one two three
2 one 2 three should return 2 and one 2 three
2,234 one two 3,000 should return 2,234 and one two 3,000
The space between parts 1 and two could be included in the beginning of part 2.
You need to use capturing groups for both first and rest. Try this regex:
Now the group 1 is your comma separated numbers and group 2 is the rest. \s+ eats the whitespace in between. (at least 1 required).
And of course, if the regex does not match at all, then it does not start with a number or comma separated list of numbers, followed by one whitespace character or more.