0

I have a text file. Sample content of that particular text file is like

root(ROOT-0, good-4)nn(management-2, company-1)nsubj(good-4, management-2)

Now i need to separate this and store it in ArrayList. For that i write the following code

public class subject {
public void getsub(String f){
    ArrayList <String>ar=new ArrayList<String>();
    String a="[a-z]([a-z]-[0-9],[a-z]-[0-9])";
    Pattern pattern=Pattern.compile(a);
    Matcher matcher=pattern.matcher(f);
    while(matcher.find()){
        if(matcher.find()){
            ar.add(matcher.group(0));
        }
    }
    System.out.println(ar.size());
    for(int i=0;i<ar.size();i++){
        System.out.println(ar.get(i));
    }



}

}

but arraylist is not getting populated. Why is that so

1 Answer 1

3

You are using unquoted parenthesis in your Pattern.

Unquoted parenthesis imply the definition of a group within your Pattern, for later back-references.

However, here you are trying to match actual parenthesis, so they need to be escaped as such: \\( and \\).

For a rough solution, try this:

String text = "root(ROOT-0, good-4)nn(management-2, company-1)nsubj(good-4, management-2)";
List<String> myPairs = new ArrayList<String>();
Pattern p = Pattern.compile(".+?\\(.+?,.+?\\)");
Matcher m = p.matcher(text);
while (m.find()) {
    myPairs.add(m.group());
}
System.out.println(myPairs);

Output:

[root(ROOT-0, good-4), nn(management-2, company-1), nsubj(good-4, management-2)]

Final note: for an improved solution, I would try and use groups to distinguish between the first part of your Pattern and the actual pair in the parenthesis, so to build a Map<String, ArrayList<String>> as a data object in this case - but this is out of scope for this answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.