fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.regex.*;
  5.  
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. String s = "My cake should have ( sixteen | sixten | six teen ) candles, I love and ( should be | would be ) puff them.";
  11. String rx = "\\(([^()]*)\\)";
  12.  
  13. StringBuffer result = new StringBuffer();
  14. Matcher m = Pattern.compile(rx).matcher(s);
  15. while (m.find()) {
  16. String add = "";
  17. String[] items = m.group(1).split("\\|");
  18. for (int i=1; i<=items.length; i++) {
  19. add += "<p id=\"" + i + "\">" + items[i-1].trim() + "</p>";
  20. }
  21. m.appendReplacement(result, "<div>"+add+"</div>");
  22. }
  23. m.appendTail(result);
  24. System.out.println(result.toString());
  25.  
  26. }
  27. }
Success #stdin #stdout 0.18s 53980KB
stdin
Standard input is empty
stdout
My cake should have <div><p id="1">sixteen</p><p id="2">sixten</p><p id="3">six teen</p></div> candles, I love and <div><p id="1">should be</p><p id="2">would be</p></div> puff them.