fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class Main
  5. {
  6. static void printMatch(String regex, String str, int... groups)
  7. {
  8. System.out.println("String = " + str);
  9. System.out.println("Regex = " + regex);
  10. Pattern p = Pattern.compile(regex);
  11. Matcher m = p.matcher(str);
  12. while (m.find())
  13. for (int i: groups)
  14. System.out.println("Group " + i + " = " + m.group(i));
  15. System.out.println();
  16. }
  17.  
  18. public static void main(String[] args) throws Exception
  19. {
  20. System.out.println("The old way:");
  21. String regex = "echo[\\t ]+\".*?(?<!\\\\)\"";
  22. String str = "echo \"\\\\\"";
  23. printMatch(regex, str, 0);
  24.  
  25. System.out.println("The new way:");
  26. regex = "echo[\\t ]+\"(\\\\.|[^\\\\])*?\"";
  27. str = "echo \"\\\\\"";
  28. printMatch(regex, str, 0);
  29. str = "some other stuff echo \"This will not \\\" work\" some other stuff";
  30. printMatch(regex, str, 0);
  31. }
  32. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
The old way:
String = echo "\\"
Regex = echo[\t ]+".*?(?<!\\)"

The new way:
String = echo "\\"
Regex = echo[\t ]+"(\\.|[^\\])*?"
Group 0 = echo "\\"

String = some other stuff echo "This will not \" work" some other stuff
Regex = echo[\t ]+"(\\.|[^\\])*?"
Group 0 = echo "This will not \" work"