User Controls

Regex For Checking If Something Is At Begging Of String

  1. #1
    SBTlauien African Astronaut
    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.
  2. #2
    SBTlauien African Astronaut
    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.
  3. #3
    Lanny Bird of Courage
    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.
  4. #4
    SBTlauien African Astronaut
    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
  5. #5
    SBTlauien African Astronaut
    The correct answer...

    .replaceFirst
Jump to Top