Nicolasllk
Nicolasllk

Reputation: 115

Regular expression not working as expected - JAVA

I am using the following regex "location in \\((.*?)\\)"

against the following string: pro 300\nlocation in ("aaa","bbb")

according to online regex test for java, the result should be "aaa","bbb" but when I run that in java code like this:

conditions.replaceAll("location in \\((.*?)\\)", "$1");

I get pro 300"aaa","bbb"

What I am doing wrong? Thanks in advance.

Upvotes: 1

Views: 255

Answers (2)

Rossiar
Rossiar

Reputation: 2564

replaceAll() is replacing the part of conditions matched by group(0) of your regex.

To retrieve only the part inside (...) you need to use:

Pattern p = Pattern.compile("location in \\((.*?)\\)");
Matcher m = p.matcher(conditions);
if (m.find())
{
    String s = m.group(1);
}

This will retrieve the inner bracket of your regular expression (.*?)

Upvotes: 7

Federico Piazza
Federico Piazza

Reputation: 30985

Additionally to Rossiar's answer, if you don't want to use Pattern and Matcher classes and just want to use replaceAll method then your code is working as expected, you have below string:

pro 300\nlocation in ("aaa","bbb")
         ^^^^^^^^^^^^^^^^^^^^^^^^^ and you replace this by "aaa","bbb"

So, your final string is:

pro 300\n"aaa","bbb"

String.replaceAll

If you want just to get "aaa","bbb" using replaceAll, you will have to match the complete string by using:

conditions = conditions.replaceAll(".*location in \\((.*?)\\).*", "$1");
                                    ^--------- Note ---------^

Or for your specific string you could use:

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll(".*\\((.*?)\\).*", "$1");

I can't test it right now if \n is not being matched by .*, so in case it isn't then you can replace multilines by using single line flag or doing a regex trick:

Single line flag

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll("(?s).*\\((.*?)\\).*", "$1");

Working demo

Regex trick

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll("[\\s\\S]*\\((.*?)\\)[\\s\\S]*", "$1");

Working demo

Upvotes: 2

Related Questions