简体   繁体   中英

How to do search and replace in Java using regex

An obvious way to handle String search and replace is

String s = "This will go over well!";
s = s.replace("go", "not go");

I wonder .. can the same be done using regex package? Are there benefits from using it?

Can something along the lines of s/go/not go/g exist?

I wonder .. can the same be done using regex package? Are there benefits from using it?

Please look at using String#replaceAll(String regex, String replacement) instead of String#replace(...) since this uses a regular expression for the first parameter. The String API will tell you more about this. This does give some added flexibility and power but with the price (I believe -- I have not profiled this) of slower execution time.

Can something along the lines of s/go/not go/g exist?

I'm not sure I understand what you're asking here. Can you please clarify this a bit?

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