Home > Net >  How to define a regex for (arg_1, arg_2, ..., arg_n) in java and use it to split a string?
How to define a regex for (arg_1, arg_2, ..., arg_n) in java and use it to split a string?

Time:12-21

I am trying to split a string that has names of couple of methods and classes in them and other information that I am trying to extract. The methods and classes are separated by : which is pretty straight forward.For methods, I only need the names and not the parameters. I am trying to define a regex to represent (...) where ... represents anything.

Here is what I have done so far:

String str = "M:org.apache.commons.math3.genetics.CycleCrossover:mate(org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome) (O)java.util.HashSet:<init>(int)";
String[] arr = line.split(":|[(&&[a-z|A-Z]&&)]");

This will give me the following:

M
org.apache.commons.math3.genetics.CycleCrossover
mate(org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome) (O)java.util.HashSet
<init>(int)

which is technically the same as using only ':' I have tried a variety of different patterns but the closet that I got to is the following:

String[] arr = line.split(":| |[(]|[)]");

which produces:

M
org.apache.commons.math3.genetics.CycleCrossover
mate
org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome


O
java.util.HashSet
<init>
int

finally what I am trying to get is;

M
org.apache.commons.math3.genetics.CycleCrossover
mate

java.util.HashSet
<init>

CodePudding user response:

Could you give this a try:

String[] arr = str.split("(\\((.*?)\\))|:|  |[(]|[)]");

should look like this now:

M
org.apache.commons.math3.genetics.CycleCrossover
mate
 
java.util.HashSet
<init>

\\( and )// which will match (). For (.*?), the .*? will match any character zero or anything and the () is the group.

  • Related