Java best way for string find and replace?

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

    Try this:

    public static void main(String[] args) {
        String str = "My name is Milan, people know me as Milan Vasic.";
    
        Pattern p = Pattern.compile("(Milan)(?! Vasic)");
        Matcher m = p.matcher(str);
    
        StringBuffer sb = new StringBuffer();
    
        while(m.find()) {
            m.appendReplacement(sb, "Milan Vasic");
        }
    
        m.appendTail(sb);
        System.out.println(sb);
    }
    
    0 讨论(0)
提交回复
热议问题