Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - Java : replacing text URL with clickable HTML link

I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.

My initial String looks like this :

"hello, i'm some text with an url like http://www.the-url.com/ and I need to have an hypertext link !"

What I want to get is a String looking like :

"hello, i'm some text with an url like <a href="http://www.the-url.com/">http://www.the-url.com/</a> and I need to have an hypertext link !"

I can catch URL with this code line :

String withUrlString = myString.replaceAll(".*://[^<>[:space:]]+[[:alnum:]/]", "<a href="null">HereWasAnURL</a>");

Maybe the regexp expression needs some correction, but it's working fine, need to test in further time.

So the question is how to keep the expression catched by the regexp and just add a what's needed to create the link : catched string

Thanks in advance for your interest and responses !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to use:

myString.replaceAll("(.*://[^<>[:space:]]+[[:alnum:]/])", "<a href="$1">HereWasAnURL</a>");

I didn't check your regex.

By using () you can create groups. The $1 indicates the group index. $1 will replace the url.

I asked a simalir question: my question
Some exemples: Capturing Text in a Group in a regular expression


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...