简体   繁体   中英

How to use string.replaceAll to change everything after a certain word

I have the following string: http://localhost:somePort/abc/soap/1.0

I want the string to just look like this: http://localhost:somePort/abc .

I want to use string.replaceAll but can't seem to get the regex right. My code looks like this: someString.replaceAll(".*\\babc\\b.*", "abc");
I'm wondering what I'm missing? I don't want to split the string or use.replaceFirst, as many solutions suggest.

It would seem to make more sense to use substring , but if you must use replaceAll , here's a way to do it.

You want to replace /abc and everything after it with just /abc .

string = string.replaceAll("/abc.*", "/abc")

If you want to be more discriminating you can include a word boundary after abc , giving you

string = string.replaceAll("/abc\\b.*", "/abc")

Just for explanation on the given regex, why it wont work:

\b \b - word boundaries are not required here and also as .* is added in the beginning it matches the whole string and when you try to replace it with "abc" it will replace the entire match with "abc". Hence you get the wrong answer. Instead, only try to match what is required and then whatever is matched that will be replaced with "abc" string.

someString.replaceAll("/abc.*", "/abc");

/abc.* - Looks specifically for /abc followed by 0 or more characters
/abc - Replaces the above match with /abc

You should use replaceFirst since after first match you are removing all after

text=  text.replaceFirst("/abc.*", "/abc");

Or

You can use indexOf to get the index of certain word and then get substring.

String findWord = "abc";
text = text.substring(0, text.indexOf(findWord) + findWord.length());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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