Java查找和替换字符串的最佳方法? [英] Java best way for string find and replace?

查看:1173
本文介绍了Java查找和替换字符串的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找用Java搜索和替换字符串的最佳方法。

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".

我想用Milan Vasic替换米兰的字符串,但在我已经使用Milan Vasic的地方,这不应该是一个案例。

I want to replace the string Milan with Milan Vasic, but on place where I have already Milan Vasic, that shouldn't be a case.

搜索/替换后的结果应该是:我的名字是Milan Vasic,人们都认为我是Milan Vasic。

after search/replace result should be: "My name is Milan Vasic, people know me as Milan Vasic".

我尝试使用indexOf()以及Pattern / Matcher组合,但我的结果都不优雅,有人有优雅的解决方案吗?

I was try to use indexOf() and also Pattern/Matcher combination, but neither of my results not looks elegant, does someone have elegant solution?

欢呼!

推荐答案

好吧,你可以使用正则表达式查找米兰未跟随Vasic的情况:

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

Milan(?! Vasic)

并用全名替换:

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

(?!...) part是否定前瞻,确保零件不遵循任何匹配在括号内。它不会消耗匹配中的任何字符。

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)

你可以用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.

这篇关于Java查找和替换字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆