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
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):
{}
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.