Java best way for string find and replace?

后端 未结 7 1433
一生所求
一生所求 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:00

    When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".

    And than replace all "Milan" Strings with "Milan Vasic".

    0 讨论(0)
  • 2021-02-03 22:13

    you can use pattern matcher as well, which will replace all in one shot.

    Pattern keyPattern = Pattern.compile(key); Matcher matcher = keyPattern.matcher(str); String nerSrting = matcher.replaceAll(value);

    0 讨论(0)
  • 2021-02-03 22:14

    Another option:

    "My name is Milan, people know me as Milan Vasic"
        .replaceAll("Milan Vasic|Milan", "Milan Vasic"))
    
    0 讨论(0)
  • 2021-02-03 22:16

    Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.

    You can view the StringUtils API at the previously linked website.

    "Don't reinvent the wheel"

    0 讨论(0)
  • 2021-02-03 22:17

    Well, you can use a regular expression to find the cases where "Milan" isn't followed by "Vasic":

    Milan(?! Vasic)
    

    and replace that by the full name:

    String.replaceAll("Milan(?! Vasic)", "Milan Vasic")
    

    The (?!...) part is a negative lookahead which ensures that whatever matches isn't followed by the part in parentheses. It doesn't consume any characters in the match itself.

    Alternatively, you can simply insert (well, technically replacing a zero-width match) the last name after the first name, unless it's followed by the last name already. This looks similar, but uses a positive lookbehind as well:

    (?<=Milan)(?! Vasic)
    

    You can replace this by just " Vasic" (note the space at the start of the string):

    String.replaceAll("(?<=Milan)(?! Vasic)", " Vasic")
    

    You can try those things out here for example.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题