Pattern p = Pattern.compile("(.+)\\s(.+)\\s(.?)$");
Matcher m = p.matcher(line);
System.out.println("Method:");
System.out.println(m.group(1));
System.out.println(m.group(2));
The code above is my code I use to split this string:
method(public, static, void) main(String[] args){
I want to be able to get method(public, static, void) in a string and main(String[] args) in another string. I don’t want the last { and there may be be spaces between the ) and the {.
My code so far does this:
Method:
method(public, static, void) main(String[]
args){
I am not any good at regex. (My code doesn’t currently handle the last {, but I can fix this.) The problem is that I cannot get the line to split how I want it to.
You don’t need
PatternandMatcherhere. You should rather useString#split()method tosplityour string on), and get first two elements of your array: –But, the problem that you can see is, your strings won’t contain the last
)in them.To include the delimiter in the array elements, you can use look-behind on your regex: –
"(?<=\\))". Now, this will split your string onempty characterpreceded by).This is what you need: –
output: –