Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Regular Expressions to split a string in Java

Tags:

java

regex

I'm attempting to find the fields in a user defined string and create an array out of them. For example, if the user enters:

abc @{fieldOne} defg @{FieldTwo} 123 @{FieldThree} zyx

I want as a result:

fields[0] = "@{fieldOne}"
fields[1] = "@{fieldTwo}"
fields[2] = "@{FieldThree}"

I've got a regular expression to find the substrings: /@{[a-zA-Z]*}/g but I have been unsuccessful in using it in Java to break up the string. Here's what I've got at the moment, and tried variations of:

String displayString = "abc @{fieldOne} defg @{FieldTwo} 123 @{FieldThree} zyx";
Pattern pattern = Pattern.compile("/@\\{[a-zA-Z]*\\}/g");
Matcher matcher = pattern.matcher(displayString);

matcher.matches() is returning false - I'm guessing the formatting of my regexp is incorrect, but I haven't been able to figure out what it should be.

Thanks in advance for comments and answers!

like image 839
Clint Avatar asked Feb 07 '23 15:02

Clint


1 Answers

No need for the forward slashes or //g modifier. Also, use double escapes.

String displayString = "abc @{fieldOne} defg @{FieldTwo} 123 @{FieldThree} zyx";

Pattern pattern = Pattern.compile("@\\{[a-zA-Z]*\\}");
Matcher matcher = pattern.matcher(displayString);
while ( matcher.find() ){
    System.out.println(matcher.group(0));
}
like image 176
copeg Avatar answered Feb 24 '23 01:02

copeg