Reputation: 6790
Given a string delimited by a colon and similar to this...
xvf:metric:admin:click
I need to capture three groups...
xvf
metric
admin:click
Or another example:
one:two:three:four:five:six:seven
one
two
three:four:five:six:seven
My current regex is just capturing each word separately, resulting in 4 matches
/(\s*\w+)/gi
Upvotes: 0
Views: 55
Reputation: 8345
And if it's possible that you get less than 3 groups, you can use
/^([^:]+)(?::([^:]+)(?::(.+)?)?)?$/
You can find an "explanation" of the RegExp here.
Upvotes: 1
Reputation: 80649
Since you're using JavaScript, it'd make more sense to actually use string.split
and later Array.slice
and Array.splice
for string manipulation:
var str = "one:two:three:four:five:six:seven",
groups = str.split(':');
groups.splice(2, groups.length, groups.slice(2).join(':'));
console.log(groups);
Upvotes: 0
Reputation: 92884
The solution using String.match
and Array.slice
functions:
var str = "one:two:three:four:five:six:seven",
groups = str.match(/([^:]+?):([^:]+?):(.+)?$/).slice(1);
console.log(groups); // ["one", "two", "three:four:five:six:seven"]
Upvotes: 1
Reputation: 4321
The solution is to capture the first two things before a :
, then capture everything after
Here's the regex:
/(.+?):(.+?):(.+)/
In code:
var testStr = "xvf:metric:admin:click";
console.log(/(.+?):(.+?):(.+)/.exec(testStr).slice(1,4))
//["xvf", "metric", "admin:click"]
Upvotes: 0