我有一个 HTML 字符串要在 WebView 中显示。我需要在每个标签中添加一个事件才能获取点击事件。我的 HTML:
<at id="user-01">Jonh</at> in group <at id="group-02">Android</at>
如何使用正则表达式添加事件
onclick="clickMention(this.id)"
在每个标签 at
中。
我想要这样的结果:
<at onclick="clickMention(this.id)" id="user-01">Jonh</at> in group <at onclick="clickMention(this.id)" id="group-02">Android</at>
或者:
<at id="user-01" onclick="clickMention(this.id)" >Jonh</at> in group <at id="group-02" onclick="clickMention(this.id)">Android</at>
最佳答案
在这里,如果我们希望使用正则表达式来完成此任务,我们可能只想将 onclick 属性放置在开始标记中的第一个空格之后,并且它可能只适用于简单的表达式:
(<at\s)
测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(<at\\s)";
final String string = "<at id=\"user-01\">Jonh</at> in group <at id=\"group-02\">Android</at>";
final String subst = "\\1onclick=\"clickMention(this.id)\" ";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
演示
const regex = /(<at\s)/gm;
const str = `<at id="user-01">Jonh</at> in group <at id="group-02">Android</at>`;
const subst = `$1onclick="clickMention(this.id)" `;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
关于java - 正则表达式在每个字符串html中添加事件onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56254902/