Nikki Nikki - 5 months ago 10
Java Question

Using Regular Expressions to split a string in Java

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!

Answer

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