简体   繁体   English

使用正则表达式替换两个定界符之间的所有字符

[英]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 "\\*" . 我已经尝试过"\\\\\\\\\\[tag=.\\*?](.\\*?)\\\\\\\\[/tag]"但这将整个序列替换为一个"\\*"
I think that "(.\\*?)" is the problem here because it captures everything at once. 我认为"(.\\*?)"是这里的问题,因为它可以一次捕获所有内容。

How would I write something that replaces every character separately? 我该如何写一些单独替换每个字符的东西?

you can use the regex 你可以使用正则表达式

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

which would match all characters before a "[\\" 会匹配“ [\\”之前的所有字符

see the regex demo , online compiler demo 参见regex演示在线编译器演示

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 : 像这样使用它将打印您的tx2预期输出:

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=.*\\\\].*)\\\\w(.*\\\\[\\\\/tag\\\\].*)"

  • (.*\\\\[tag=.*\\\\].*) capture the beginning, with eventually some char in the middle (.*\\\\[tag=.*\\\\].*)捕获开始,最终在中间出现一些字符
  • \\\\w is for the char you want to replace \\\\w是您要替换的字符
  • (.*\\\\[\\\\/tag\\\\].*) capture the end, with eventually some char in the middle (.*\\\\[\\\\/tag\\\\].*)捕获结尾,最后在中间插入一些字符

The substitution $1*$2 : 替换$1*$2

The pattern is (text$1)oneChar(text$2) and it will replace by (text$1)*(text$2) 该模式为(text$1)oneChar(text$2) ,它将替换为(text$1)*(text$2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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