Doubt about regex

Asked

Viewed 79 times

3

Have this string and I need to go through it taking only the values that are inside the (). To string is :

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

I rode the next regex:

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

Only he’s returning the matcher.group always with empty value.

1 answer

3


Those quotation marks are weird, this is the problem?

Only to summarize the possible problem should be the lack of escape in the parentheses, because they are used for match groups, if not escape it will always interpret as grouper and not as parentheses (one should use the exhaust twice like this \\), outside that the use of pattern seems to be wrong (I don’t know the class much). regexp also has a problem, I used @guilhermelautert’s suggestion (\(([^)]*)\))

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);
        }
    }
}
  • > illegal escape Character in string literal

  • @Gabrielsouza which?

  • @Gabrielsouza edited the example, just need to correct the regex, I’m trying here, just a minute

  • 1

    You have a problem with this REGEX, Original, Option 1, Option 2, recommend the Option 2.

  • @Guilhermelautert .. option 2 takes the parentheses together. I only need what’s inside them.

  • 1

    @Gabrielsouza Thus? the content is in group 1.

  • @Guilhermelautert Perfect. Thank you very much.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.