Doubt on regex

3

Have this string and need to scroll through it by taking only the values that are within () . The string is:

String estados = “(1, ‘AC', ‘Acre’), (2,’AL', ‘Alagoas’), (3, AM, ‘Amazonas’)… “

I've mounted the following regex :

Pattern pattern = pattern.compile(“(([^>]*))”);    
Matcher matcher = pattern.matcher(estados);    
while(matcher.find()){    
  String aux = matcher.group();    
  …    
}

Only it is returning matcher.group always with empty value.

    
asked by anonymous 07.10.2016 / 16:00

1 answer

3

These quotation marks are strange, is this the problem?

Just to summarize the possible problem should be the lack of escape in the parentheses, as they are used for match groups, if not escape it will always interpret as a grouper and not as parentheses (one must use the escape twice as well \ ), except that pattern seems to be wrong (I do not know much about the class). The regexp also has a problem, I used the suggestion of @guilhermelautert ( \(([^)]*)\) )

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* Name of the class has to be "Main" only if the class is public. */
class Exemplo
{
    public static void main (String[] args)
    {
        String estados = "(1, 'AC', 'Acre'), (2, 'AL', 'Alagoas'), (3, AM, 'Amazonas')";

        Pattern p = Pattern.compile("\(([^)]*)\)");
        Matcher matcher = p.matcher(estados);

        while (matcher.find()) {    
          String aux = matcher.group();
          System.out.println(matcher);
        }
    }
}
    
07.10.2016 / 16:07