Nepha
Nepha

Reputation: 33

Replace all characters between two delimiters using regex

I'm trying to replace all characters between two delimiters with another character using regex. The replacement should have the same length as the removed string.

String string1 = "any prefix [tag=foo]bar[/tag] any suffix";
String string2 = "any prefix [tag=foo]longerbar[/tag] any suffix";
String output1 = string1.replaceAll(???, "*");
String output2 = string2.replaceAll(???, "*");

The expected outputs would be:

output1: "any prefix [tag=foo]***[/tag] any suffix"  
output2: "any prefix [tag=foo]*********[/tag] any suffix"

I've tried "\\\\\[tag=.\*?](.\*?)\\\\[/tag]" but this replaces the whole sequence with a single "\*".
I think that "(.\*?)" is the problem here because it captures everything at once.

How would I write something that replaces every character separately?

Upvotes: 1

Views: 3757

Answers (2)

marvel308
marvel308

Reputation: 10458

you can use the regex

\w(?=\w*?\[)

which would match all characters before a "[\"

see the regex demo, online compiler demo

Upvotes: 3

azro
azro

Reputation: 54148

You can capture the chars inside, one by one and replace them by * :

public static String replaceByStar(String str) {
    String pattern = "(.*\\[tag=.*\\].*)\\w(.*\\[\\/tag\\].*)";
    while (str.matches(pattern)) {
        str = str.replaceAll(pattern, "$1*$2");
    }
    return str;
}

Use like this it will print your tx2 expected outputs :

public static void main(String[] args) {
    System.out.println(replaceByStar("any prefix [tag=foo]bar[/tag] any suffix"));
    System.out.println(replaceByStar("any prefix [tag=foo]loooongerbar[/tag] any suffix"));
}

So the pattern "(.*\\[tag=.*\\].*)\\w(.*\\[\\/tag\\].*)" :

  • (.*\\[tag=.*\\].*) capture the beginning, with eventually some char in the middle
  • \\w is for the char you want to replace
  • (.*\\[\\/tag\\].*) capture the end, with eventually some char in the middle

The substitution $1*$2:

The pattern is (text$1)oneChar(text$2) and it will replace by (text$1)*(text$2)

Upvotes: 2

Related Questions