fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. class Ideone
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. String s = "Today [#[#item#] was|the items were#] shipped so [#it is|they are#] gone.";
  12. System.out.println(convert(s, true));
  13. System.out.println(convert(s, false));
  14. }
  15.  
  16. public static String convert(String text, boolean isSingular) {
  17. Pattern spPattern = Pattern.compile("\\[#((?:\\[#.*?#]|(?!#])[^|])*?)\\|((?:\\[#.*?#]|(?!#])[^|])*?)#]");
  18. Matcher matcher = spPattern.matcher(text);
  19. while (matcher.find()) {
  20. String replacement = isSingular ? matcher.group(1) : matcher.group(2);
  21. text = matcher.replaceFirst(replacement);
  22. matcher = spPattern.matcher(text);
  23. }
  24. return text;
  25. }
  26. }
Success #stdin #stdout 0.1s 27920KB
stdin
Standard input is empty
stdout
Today [#item#] was shipped so it is gone.
Today the items were shipped so they are gone.