0

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?

3
  • Do you want href="/1" in all 3 cases? Commented Sep 16, 2014 at 7:29
  • sorry, I modified it now Commented Sep 16, 2014 at 7:31
  • Thanks for update, posted an answer with demo. Commented Sep 16, 2014 at 7:34

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

+1. I was thinking of doing this then decided to go down the Matcher.appendReplacement route - can't quite remember why. This is much shorter!
1

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>

2 Comments

sorry, but i want the string to be < a href="/{num}">#{num}< /a>
thank you for your answer , it is my fault. I am sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.