Java best way for string find and replace?

后端 未结 7 1451
一生所求
一生所求 2021-02-03 21:38

I\'m looking for the best approach for string find and replace in Java.

This is a sentence: \"My name is Milan, people know me as Milan Vasic\".

I want to repla

7条回答
  •  无人共我
    2021-02-03 22:17

    One possibility, reducing the longer form before expanding all:

    string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")
    

    Another way, treating Vasic as optional:

    string.replaceAll("Milan( Vasic)?", "Milan Vasic")
    

    Others have described solutions based on lookahead or alternation.

提交回复
热议问题