To search for words between brackets, I use the following code:

final String str = "([word1]word2 {word3})"; final Matcher m = Pattern.compile("(\\(|\\[|\\{)(.*?)(\\)|\\]|\\})").matcher(str); while (m.find()) { System.out.println(m.group(2)); } 

The bottom line is that my whole expression is wrapped in parentheses and, as planned, everything should be displayed in the result, but the conclusion is:

[word1 word3

I can not write a regular expression, so that it would produce everything that is between the outermost brackets, and if they are missing, just the words in brackets from the string (that is, word1 and word3). Help me please.

  • one
    Are you sure you want to do this with a single expression? it will simply confuse the one who will look at it all in six months or a year (perhaps it will be you yourself). Why not split this expression into several? - Mikhail Vaysman
  • IMHO, the task is simpler, clearer, and most importantly - more reliably solved without regexps. In any case, your version does not take into account unpaired situations like [word} in the simplest case, not to mention nested brackets. - PinkTux

1 answer 1

In general, he solved his problem. I had as advised to break into two expressions. First, I check if the string is wrapped with external brackets, with the help of matches, if not, then with the help of find, find the bracket in the string. The clearString method just clears unnecessary spaces and other characters

  public static List<String> getWords(final String str) { final List<String> words = new ArrayList<>(); Matcher m = Pattern.compile("\\W(\\(|\\[|\\{)(.*?)(\\)|\\]|\\})\\W").matcher(str); if (m.matches()) { words.addAll(Arrays.asList(Brackets.clearString(m.group(0)).split(" "))); } else { m = Pattern.compile("(\\(|\\[|\\{)(.*?)(\\)|\\]|\\})").matcher(str); while (m.find()) { words.add(Brackets.clearString(m.group(0))); } } return words; }