Consider the string
String s = "H_ello pe_rfec_t wor_ld"
I want to replace all '_' symbols on... no matter what, let`s say on '1', except those which are placed inside the 'pe_rfec_t'. I could not find any solution even to just skip the word 'pe_rfec_t':
s = s.replaceAll("(?<=pe_rfec_t).*|.*(?=pe_rfec_t)", "1");
looks nice at a glance but results to:
11pe_rfec_t1 //instead of 1111111pe_rfec_t1111111
Ideally I need the following result:
Hello pe_rfec_t world
Could anyone help me please?
You can use alternation and captured group:
String str = "H_ello pe_rfec_t wor_ld";
String repl = str.replaceAll("(pe_rfec_t)|_", "$1");
//=> Hello pe_rfec_t world
Here in alternation we match first pe_rfec_t
and capture it in group #1. In repalcement we put $1
(back-reference to group #1) back.
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.