Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex Matcher works, but String.split() doesn't

Tags:

java

regex

I am looking to use a one line String.split() to pull out the 'name' in a query I am writting..

The Pattern + Matcher works like expected, but I am pulling my hair out trying to figure out why String.split() doesn't return a match!

public static void main(String[] asdf)
{
    final String queryText = "id <equals> `1` <AND> name <equals> `some name`";
    final String regex = "^(.*name <equals> `)([\\S\\s]*)(`.*)$";

    System.out.println("Splitting...");
    final String[] split = queryText.split(regex);
    for (int i = 0; i < split.length; i++)
    {
        System.out.println(split[i]);
    }

    System.out.println("Matching...");
    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher(queryText);

    if (matcher.find())
    {
        for (int i = 0; i < matcher.groupCount(); i++)
        {
            System.out.println(matcher.group(i + 1));
        }
    }
}

Prints the output

Splitting...
Matching...
id <equals> `1` <AND> name <equals> `
some name
`
like image 220
Thomas Beauvais Avatar asked Mar 06 '26 18:03

Thomas Beauvais


1 Answers

You regex matches the whole string. Thus, when splitting, the whole string gets removed. It is exactly the same as "a".split("a"), which returns an empty array.

What you could use instead is:

queryText.replaceAll(".*name <equals> `([^`]+)`.*", "$1")

which returns some name.

like image 69
sp00m Avatar answered Mar 09 '26 06:03

sp00m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!