Consider the following string method<arg1,arg2,arg3>
I would like to use RegEx to get the portions method
, arg1
, arg2
, arg3
from this string.
The following regex /([a-z0-9]+)<(?:([a-z0-9]+),?)*>/i
matches the string as a whole.
That is,
var result = /([a-z0-9]+)<(?:([a-z0-9]+),?)*>/i.test('method<arg1,arg2,arg3>');
// result = true
But, regEx.exec
method returns only method
, arg3
portions.
result = /([a-z0-9]+)<(?:([a-z0-9]+),?)*>/i.exec('method<arg1,arg2,arg3>');
// result is ["methodname<arg1,arg2,arg3>", "methodname", "arg3"]
// as opposed to
// ["methodname<arg1,arg2,arg3>", "methodname", "arg1", "arg2", "arg3"]
Is there a way to get all the matches of a group?
Note: I am asking this for the purpose of learning and I do not want a JavaScript work around.
Edit: The number of args (arg1, arg2, etc.) is arbitrary and can change in different cases.
You need to split this up into two expressions, one for the outer string and one for the inner; though, the inner expression can be simplified to just a regular string split.
var str = 'method<arg1,arg2,arg3>',
outer_re = /(\w+)<([^>]*)>/g;
while ((match = outer_re.exec(str)) !== null) {
var fn = match[1],
args = match[2].split(',');
console.log(fn, args);
}
Btw, this is able to match multiple method occurrences, eg:
"method1<arg1> method2<arg1,arg2>"
If this is not necessary you can anchor the expression:
/^([^<]+)<([^>]*)>$/;
Try out this regex
\\b([^<]*)<([^,]*),([^,]*),([^>]*)>
Captured groups:
0: "method<arg1,arg2,arg3>"
1: "method"
2: "arg1"
3: "arg2"
4: "arg3"
\\b([^<]*)<([^>]*)>
pulls out the name and all arguments.
Captured groups:
0: "method<arg1,arg2,arg3>"
1: "method"
2: "arg1,arg2,arg3"
Then I'd simply split the group 2 on the known delimiter ,
The following will work:
input = "method<arg1,arg2,arg3>";
action = input.match (/^(\w*)\s*<\s*(.*)?\s*>$/);
action[2] = action[2].split (/\s*,\s*/); // array of args
;; processing method action[1] and arguments action[2] (an array)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.