Reputation: 1055
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
Reputation: 174706
Use capturing group to capture the #
along with the following number.
Regex:
(#(\\d+))
Replacement string:
< a href="/$2">$1< /a>
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
Reputation: 785186
This Java code should work:
String repl = input.replaceAll("(?<!>)#(\\d+)(?!<)", "<a href=\"/$1\">#$1</a>");
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