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
`
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With