简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM