jcstock74
jcstock74

Reputation: 215

Java Regular Expression code to process {Item1}.Item2 into array or list

Can anyone give me some advice into how to use Java RegEx to process:

{Item1}.Item2

so that I get an array or list containing

I was thinking of a RegEx like:

   Pattern p = Pattern.compile("\\{(.+?)\\}\\.(.*?)");     
   Matcher match = p.matcher(mnemonicExpression); 
   while(match.find()) {     
    System.out.println(match.group());    
   }   

But this does not seem to work.

Any help would be much appreciated.

Kind Regards

jcstock74

Upvotes: 1

Views: 254

Answers (2)

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

Bonus answer: This web page has a very nice regular expression tester using java.util.regex. This is the best way to test your expressions and it even provides the escaped java String you would use in Pattern.compile():

http://www.regexplanet.com/simple/index.html

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170227

You need to grab the individual match groups 1 and 2. By using group(), you're effectively doing group(0), which is the entire match. Also, the last .*? shouldn't be reluctant, otherwise, it matches just an empty string.

Try this:

Pattern p = Pattern.compile("^\\{(.+?)\\}\\.(.*)$");
//                                \ /        \/
//                                 1          2

Matcher match = p.matcher("{Item1}.Item2");
while(match.find()) {
  System.out.println("1 = " + match.group(1));
  System.out.println("2 = " + match.group(2));
}

which produces:

1 = Item1
2 = Item2

Upvotes: 4

Related Questions