Regex добавить событие onclick в каждой строке html - PullRequest
0 голосов
/ 22 мая 2019

У меня есть строка 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>

Ответы [ 2 ]

0 голосов
/ 23 мая 2019

Спасибо всем, я сделал это с кодом:

String myString ="<at id =\"14\">Tran Bien </at><at id =\"14\">Tran Bien </at>";
String regex="<at(.*?)>(.*?)</at>";
String out = myString.replaceAll(regex,"<at $1 onclick=\"clickMention(this.id)\">$2</at>");
0 голосов
/ 22 мая 2019

Здесь, если мы хотим выполнить эту задачу с регулярными выражениями, мы можем просто захотеть поместить атрибут onclick после первого пробела в открывающих тегах, и он может просто работать с простым выражением:

(<at\s)

enter image description here

Test

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...