Sachin Verma
Sachin Verma

Reputation: 3802

Regex compilation in intellij

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

Answers (3)

Yassin Hajaj
Yassin Hajaj

Reputation: 21965

This is NOT a compilation error that you receive. It's an inspection from IntelliJ, even though it's underlined in red.

enter image description here

You may disable the inspection by going into your settings

enter image description here

Upvotes: 1

ernest_k
ernest_k

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):

enter image description here

Upvotes: 4

Pavneet_Singh
Pavneet_Singh

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

Related Questions