Reputation: 3802
I am trying to do:
uri=uri.replaceFirst("{}",param.toString());
I'm supposed to use regex in place of {}
but that should not be a compilation problem because method signature takes String and {}
is a perfectly valid string. Below is replaceFirst()
:
public String replaceFirst(String regex, String replacement)
Help me understand how is this a compilation error.
IntellijIDEA 2018.1
Upvotes: 3
Views: 299
Reputation: 21965
This is NOT a compilation error that you receive. It's an inspection from IntelliJ, even though it's underlined in red.
You may disable the inspection by going into your settings
Upvotes: 1
Reputation: 45309
The first parameter is expected to be a valid regex. Because there are metacharacters, you must escape:
uri=uri.replaceFirst("\\{\\}",param.toString());
IntelliJ does inspection that allows it to report such errors. This is an IDE feature. Compiling this code with javac
wouldn't cause it to fail.
You can disable inspection (alt+enter, details on the page linked to above):
Upvotes: 4
Reputation: 37404
{}
is a special regex character which represents the range operator so you have to escape it before using it
// normal use
"".replaceFirst("a{1,2}","");
As shown, {}
is recognised as range to match minimum and maximum occurrences of a
so while using regex you have to provide some character/word along with minimum and maximum value with range operator {}
(otherwise it can cause regex engine to crash or behave unexpectedly so compiler is being proactive here)
solution : escape it using \\
uri = uri.replaceFirst("\\{\\}",param.toString());
Upvotes: 3