Reputation: 2725
Suppose we have string like this
{"className":"first","i":0,"name":null}
How to convert it into:
{"className":"second","i":0,"name":null}
I have this one:
///Initialy className is a className in lower Case (for example "first")
className = "\"className\":\""+className+"\",";
string.replaceAll( "\"className\":\".+\"" ,className);
But it gives:
{"className":"second",:null}
Upvotes: 0
Views: 1263
Reputation: 248
Replace below statement string.replaceAll( "\"className\":\".+\"" ,className);
with string.replaceAll( "\"className\":\".+\""+"," ,className);
It gives.
{"className":"second","i":0,"name":null}
Upvotes: 1
Reputation: 31699
Your regex has ".+"
in it. +
is a "greedy" quantifier, which means that .+
will match the largest possible number of characters. So the matcher will look all the way to the furthest quote mark it can. If, instead, you want to match the smallest possible number of characters, add ?
after the quantifier, i.e.
string.replaceAll( "\"className\":\".+?\"" ,className);
In Java this is called a "reluctant" qualifier. (I've seen it called other names as well.)
I agree with the comments that a regex is not the best approach for this problem.
Upvotes: 2