a.parfenov a.parfenov - 1 year ago 64
Java Question

How to skip a specific word when replace the String using regexp in java

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?

Answer Source

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

RegEx Demo

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download