regexp to match string with (comma-separated) number at start and to split into number and rest?
Posted
by
mix
on Stack Overflow
See other posts from Stack Overflow
or by mix
Published on 2012-06-27T20:58:40Z
Indexed on
2012/06/27
21:16 UTC
Read the original article
Hit count: 174
JavaScript
|regex
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.
© Stack Overflow or respective owner