如何重复图案?

时间:2019-10-15 04:40:14

标签: java regex

我正在尝试通过正则表达式用空格替换某些单词。 例如,我有以下代码用空格替换单词"onerror=error="

String content = "ononerror=error=";
Pattern scriptPattern = Pattern.compile("onerror(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
content = scriptPattern.matcher(content).replaceAll("");

如果运行上述代码,则仅保留“ onerror”。

但是我想替换它,并用空格替换再次出现的“错误”。

换句话说,我想用正则表达式替换“ onerror”,最后只留下一个空格。

我不知道要搜索哪个关键字,所以我问一个问题。请帮助我。


此代码使用find()重写。请注意。

Pattern scriptPattern = Pattern.compile("onerror(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
while (scriptPattern.matcher(content).find()) {
    content = scriptPattern.matcher(content).replaceAll("");
}

scriptPattern = Pattern.compile("onchange(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
while (scriptPattern.matcher(content).find()) {
    content = scriptPattern.matcher(content).replaceAll("");
}

scriptPattern = Pattern.compile("onclick(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
while (scriptPattern.matcher(content).find()) {
    content = scriptPattern.matcher(content).replaceAll("");
}

1 个答案:

答案 0 :(得分:0)

使用find()的循环可以达到目的:

String content = "ononerror=error=";
Pattern scriptPattern = Pattern.compile("onerror(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
while (scriptPattern.matcher(content).find()) {
    content = scriptPattern.matcher(content).replaceAll("");
}