TomSelleck
TomSelleck

Reputation: 6968

Extract words between parentheses

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){};
    }
}

Upvotes: 0

Views: 2572

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200148

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.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

You are skipping every second line. Read each line once.

String parseMe;
while((parseMe = bufferedReader.readLine()) != null) {
    Matcher regexMatcher = regex.matcher(parseMe);

I would remove the try/catch block as it doesn't do anything useful. You can have main thorws IOException instead.

Upvotes: 3

Related Questions