I am trying to solve a fairly easy problem but can’t quite figure out how to use regexs properly. I want to extract any words from a text file between (parentheses). This was the sort of attempt I have going. Any shove in the right direction would be appreciated!!
public class Reader {
public static void main(String[] args) {
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\{([^}]*)\\}");
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader("test2.txt"));
while(bufferedReader.readLine()!=null)
{
String parseMe = bufferedReader.readLine();
Matcher regexMatcher = regex.matcher(parseMe);
while (regexMatcher.find())
{
matchList.add(regexMatcher.group());
}
}
System.out.println(matchList);
}catch(IOException e){};
}
}
The regex string should (at least) be
"[({\\[].*?[\\]})]"The outer square brackets are regex syntax — you are defining a character class to look for. It’s not perfect and a completely correct solution is impossible in Java regex (you can’t account for nested brackets). But there’s a start 🙂 BTW you may find it useful to experiment with the regex using Eclipse Find. It’s even got a great content assist.