I'm very new to regular expressions. My string looks like this:
"6 years, 10 months, 1 days, 23 hours, 15 seconds"
and basically I'd likd to match every section of times and words so the resulting array from javascripts string.match looks like this:
[0] = "6 years"
[1] = "10 months"
[2] = "1 days"
[3] = "23 hours"
[4] = "15 seconds"
Here's what I've attempted
/(\d{0,}\s(years|months|hours|days|seconds))/
but this regex tester shows I'm catching each of the words as well in my backreference
/(\d{0,}\s\w*)\,{0}/
and when I try to match to the ma it just goes all over the place.
I'm not sure how exactly to go about this and the explanations I've read in matching whole word patterns haven't been very clear either.
As always, Thanks everyone!
I'm very new to regular expressions. My string looks like this:
"6 years, 10 months, 1 days, 23 hours, 15 seconds"
and basically I'd likd to match every section of times and words so the resulting array from javascripts string.match looks like this:
[0] = "6 years"
[1] = "10 months"
[2] = "1 days"
[3] = "23 hours"
[4] = "15 seconds"
Here's what I've attempted
/(\d{0,}\s(years|months|hours|days|seconds))/
but this regex tester shows I'm catching each of the words as well in my backreference http://rubular./r/qkyFJrBCq8
/(\d{0,}\s\w*)\,{0}/
and when I try to match to the ma it just goes all over the place. http://rubular./r/PXoPHVibH0
I'm not sure how exactly to go about this and the explanations I've read in matching whole word patterns haven't been very clear either.
As always, Thanks everyone!
([^,]+)
which creates groups around the non-ma characters. See my example.
– ChrisP
Commented
Jun 5, 2013 at 23:29
You could just use split with a much more simple regex for the delimiter:
var str = '6 years, 10 months, 1 days, 23 hours, 15 seconds';
var result = str.split(/,\s*/g);
The ,\s*
regular expression just matches a ma followed by any number of spaces.
Paulpro's answer seems to be the best here, but non-capturing parentheses (?:
should also work for you:
/(\d+\s(?:years|months|hours|days|seconds))/
how about you use split
function?
for regex you can simply use this pattern:
/[0-9]+\s*[a-z]/i
If you actually want to match the pattern you have, the main problem with your regex is the way parentheses are placed. This pattern will match a single number-unit bination:
/(\d+\s((years)|(months)|(hours)|(days)|(seconds)))/
Per this answer on SO, use the g
flag with your regular expression to make a global match. The results are returned conveniently in an array:
var re = /(\d+\s(?:years|months|hours|days|seconds))/g;
var str = "6 years, 10 months, 1 days, 23 hours, 15 seconds";
var myArray = str.match(re);
alert(myArray);
Note that exec
returns one match at a time, while match
returns all matches at once in an array.
See live demo here.