java - 正则表达式在每个字符串html中添加事件onclick

标签 java html regex

我有一个 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)

enter image description here

测试

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/

相关文章:

java - 处理自定义注释

java - 如何从父类(super class)扩展内容? ( java )

Java:如何从 <?扩展 ...> 到 <E>

javascript - 如何使用 HTML5 SSE 发送 json_encode 数据

regex - 如何在Elasticsearch中编写此查询

java - 短语的正则表达式包含文字和数字,但并非所有短语都是仅具有固定范围长度的数字

Java 事件与 C# - Java 新手

javascript - 如何进行部分页面重新加载?

html - 表格单元格在 Google Chrome PC 中丢失边框

Python多次重复错误