-1

I have an HTML string to display in WebView. I need add an event in each tag to get an event on click. My HTML:

<at id="user-01">Jonh</at> in group <at id="group-02">Android</at>

How I can use a regex to add the event

onclick="clickMention(this.id)"

in each tag at of this.

I want a result like:

<at onclick="clickMention(this.id)" id="user-01">Jonh</at> in group <at onclick="clickMention(this.id)" id="group-02">Android</at>

or:

<at id="user-01" onclick="clickMention(this.id)" >Jonh</at> in group <at id="group-02" onclick="clickMention(this.id)">Android</at>
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Hoa.Tran
  • 935
  • 10
  • 26

2 Answers2

0

Here, if we wish to do this task with regular expressions, we might just want to place the onclick attribute after the first space in the opening tags and it might just work with a simple expression:

(<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);

Demo

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

Emma
  • 27,428
  • 11
  • 44
  • 69
0

Thank you every one, I did it with code:

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>");
Hoa.Tran
  • 935
  • 10
  • 26