简体   繁体   中英

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

  • Item1
  • Item2

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

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

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

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