Getting multiple matches for a group in RegEx

Consider the following line method<arg1,arg2,arg3>

I would like to use RegEx to get the parts of method , arg1 , arg2 , arg3 from this line.

The following regex /([a-z0-9]+)<(?:([a-z0-9]+),?)*>/i corresponds to the entire string.

I.e

 var result = /([a-z0-9]+)<(?:([a-z0-9]+),?)*>/i.test('method<arg1,arg2,arg3>'); // result = true 

But the regEx.exec method returns only parts of method , arg3 .

 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 group matches?

Note: I am asking for this for training purposes and I do not want to work with JavaScript.

Edit: The number of arguments (arg1, arg2, etc.) is arbitrary and can vary in different cases.

+4
source share
3 answers

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) 
0
source

You need to break this down into two expressions: one for the outer string and one for the inner; although the inner expression can be simplified to simple regular line breaks.

 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); } 

Demo

Btw, it is able to match multiple occurrences of a method, for example:

 "method1<arg1> method2<arg1,arg2>" 

If this is not necessary, you can bind the expression:

 /^([^<]+)<([^>]*)>$/; 
+2
source

Try this regex

\b([^<]*)<([^,]*),([^,]*),([^>]*)>

enter image description here

Captured groups:

 0: "method<arg1,arg2,arg3>" 1: "method" 2: "arg1" 3: "arg2" 4: "arg3" 

Any number of arguments

\b([^<]*)<([^>]*)> prints the name and all arguments.

enter image description here

Captured groups:

 0: "method<arg1,arg2,arg3>" 1: "method" 2: "arg1,arg2,arg3" 

Then I would just split group 2 into a known delimiter ,

+1
source

Source: https://habr.com/ru/post/1480967/


All Articles