2017-01-29 at 8:30 AM UTC
I have a string like "Bob is a faggot and Bob must die" and I need to replace "Bob" with "Bobby" but the first "Bob" needs to be changed to "Somebody".
So the string will become "Somebody is a faggot and Bobby must die".
What regular expression will do this for me? I'm assuming it's look behind, but I don't know how to check for the begging of the string using regex.
2017-01-29 at 8:36 AM UTC
Oh nevermind. It's actually ^Bob. But how would I put this into .replace? I tried escaping but it appears as if it's just part of the string.
2017-01-29 at 8:38 AM UTC
I don't know if there's any way to do a conditional match on a backreference. My first impulse would be to do a compound regex like `^(Someone is a faggot and Bobby|Bob is a faggot and Bob) must die` so you're effectively saying 'if you start with "someone" and use "bobby" later OR if you use "bob" twice' match this string, as opposed to trying to express "bobby is acceptable if someone was used earlier". At some point you might consider more sophisticated parsing models than regular expressions if you find more rules of this kind come into play.
2017-01-29 at 8:41 AM UTC
I'm going to try using Pattern.quote("^Bob") and see the results...
Didn't work.
Post last edited by SBTlauien at 2017-01-29T08:44:53.107771+00:00
2017-01-30 at 5:03 AM UTC
The correct answer...
.replaceFirst