using parenthesis replaceAll method Java

2019-03-04 05:24发布

问题:

I would like to change a word in a sentence, but the word has parenthesis. I keep it in the String variable. Inside of the variable st I have

manages(P0,MT0)

Inside of other String variable DES I have the following sentence:

query(MT0, P0) :- not(manages(P0,MT0)), ins_manages(P0,MT0), not(physician(P0)), not(ins_physician(P0))

SO I have another string variable querypart which stores the new word:

managesa

What I tried in the code was:

EDC = EDC.replaceAll(st,querypart);

but it did not work.

I thought the problem might be paranthesis, so I changed the string like st variable like:

manages\\(P0,MT0\\)

then I tried

EDC = EDC.replaceAll(st,querypart);

but I had the some result. The problem is when I use the replaceAll like that:

EDC = EDC.replaceAll("manages\\(P0,MT0\\)",querypart);

The sentence changes

query(MT0, P0) :- not(managesa), ins_manages(P0,MT0), not(physician(P0)), not(ins_physician(P0))

I guess it is because of parenthesis but I could not find any solution for that? What is the solution?

回答1:

I believe you wanted to use String#replace() (not replaceAll), this

String EDC = "query(MT0, P0) :- not(manages(P0,MT0)), "
    + "ins_manages(P0,MT0), not(physician(P0)), not(ins_physician(P0))";
String queryPart = "managesa";
EDC = EDC.replace("manages(P0,MT0)", queryPart);
System.out.println(EDC);

Output is

query(MT0, P0) :- not(managesa), ins_managesa, not(physician(P0)), not(ins_physician(P0))