xierui
xierui

Reputation: 1055

how to replace string with different replacement in java

Now I have a String like this

it is #1, or #2, or #3

I want to transfer it to this:

it is < a href="/1">#1< /a>, or #< a href="/2">#2< /a>, or < a href="/3">#3< /a>

So I want to replace the word "#{num}" to "< a href="/{num}">#{num}< /a>"

What shall I do?

Upvotes: 0

Views: 56

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Use capturing group to capture the # along with the following number.

Regex:

(#(\\d+))

Replacement string:

< a href="/$2">$1< /a>

DEMO

String str = "it is #1, or #2, or #3";
System.out.println(str.replaceAll("(#(\\d+))", "< a href=\"/$2\">$1< /a>"));

Output:

it is < a href="/1">#1< /a>, or < a href="/2">#2< /a>, or < a href="/3">#3< /a>

Upvotes: 1

anubhava
anubhava

Reputation: 785186

This Java code should work:

String repl = input.replaceAll("(?<!>)#(\\d+)(?!<)", "<a href=\"/$1\">#$1</a>");

RegEx Demo

PS: I have added lookaheads to make sure we don't replace a string with hyperlinks like: it is <a href="/1">#1</a> (check demo link for an example).

Upvotes: 2

Related Questions