简体   繁体   English

使用正则表达式替换特定字符串-Java

[英]Using regex to replace a certain string - Java

My goal is to replace a certain substring within a string that doesn't alter those that aren't strictly that substring. 我的目标是在字符串中替换某个特定的子字符串,而不会改变那些不是严格意义上的子字符串。 It is slightly confusing to write down so let me show you with an example. 写下来有点令人困惑,所以让我向您展示一个例子。

Say I have the string 说我有琴弦

"StackOverflow Stack Overflow Stacks"

Now I would like to replace "Stack" , if I am to use 现在,如果要使用,我想替换"Stack"

x.replaceAll("Stack", "")

I will get 我会得到

"Overflow  Overflow s"

which is not desired, instead I would like the following: 这是不希望的,相反,我想要以下内容:

"StackOverflow Overflow Stacks"

使用单词边界

\\bStack\\b

Your requirement is not entirely clear. 您的要求并不完全清楚。

You need to think about the conditions for "Stack" to be replaced. 您需要考虑替换"Stack"的条件。

A good example would be a word boundary: x.replaceAll("\\\\bStack\\\\b", "") 一个很好的例子是单词边界: x.replaceAll("\\\\bStack\\\\b", "")

This will ensure that "Stack" surrounded by non-word characters will be replaced, while other instances of "Stack" will be left untouched. 这将确保替换由非单词字符包围的"Stack" ,而其他"Stack"实例将保持不变。

You may want to be more specific and only replace when surrounded by whitespace: 您可能需要更具体,仅在被空格包围时才替换:

  • x.replaceAll("(?<=\\\\s)Stack(?=\\\\s)", "") // replaces only "Stack"
  • x.replaceAll("\\\\sStack\\\\s", "") // also gets rid of the surrounding whitespace

Etc... 等等...

You can use word boundaries to accomplish this: 您可以使用单词边界来完成此操作:

use the below code for the same: 同样使用以下代码:

String abc = "StackOverflow Stack Overflow Stacks";
abc = abc.replaceAll("\\bStack\\b", "");

System.out.println(abc);

The result is printed as StackOverflow Overflow Stacks 结果打印为StackOverflow溢出堆栈

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM