fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. final String regex = "(?<=1.*\\[)\\w+(?=\\])";
  15. final String string = "I have a string line: 1aa[appleax]bb[appley]\n\n"
  16. + "I want to capture both applex and appley via regex and if there are more - I want to capture them too. I want words between brackets.\n\n"
  17. + "Here is a catch: I want to capture them only if they go after 1. If they go before 1 - I am not interested.\n\n"
  18. + "I've tried these 2 approaches (below) but they either give me applex or appley (greedy/lazy). But I want all of them. Does anybody know what I can use?\n\n"
  19. + "Approaches I've tried:\n\n"
  20. + "Catches only applex: 1.*?\\[(\\w*)\\]\n"
  21. + "Catches only appley: 1.*\\[(\\w*)\\]";
  22.  
  23. final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
  24. final Matcher matcher = pattern.matcher(string);
  25.  
  26. while (matcher.find()) {
  27. System.out.println("Full match: " + matcher.group(0));
  28.  
  29. for (int i = 1; i <= matcher.groupCount(); i++) {
  30. System.out.println("Group " + i + ": " + matcher.group(i));
  31. }
  32. }
  33. }
  34. }
Success #stdin #stdout 0.23s 61120KB
stdin
Standard input is empty
stdout
Full match: appleax
Full match: appley