Android 正则表达式文本 url 转换为可点击 link
Android Regex text url to convert as clickable link
我对正则表达式字符串和操作非常陌生。但是我正在尝试开发一个 android 应用程序,它需要将文本 url (没有标签)从整个字符串替换为
<a href='$link'>$link </a>
我发现工作代码 -
text_to_url= text_to_url.replaceAll("(<a[^>]+>)|(http(?s)://.*)", "<a href=\"[=14=]\">[=14=]</a>");
但正如我在上面承认的那样,我对正则表达式单词和函数非常陌生。
即使我可以使用该代码获得 url 内部标记,但它不会在 url 结束时停止(我认为根据 *)。
问题是,如果有2个或更多连续的link_text_urls并排或逐行显示为一个link(url是第一个发生 url) .
我尝试了很多次并通过谷歌搜索找到了这个结果。但是我的正则表达式知识无法帮助我找到它。
请告诉我答案。非常感谢您理解我的问题。
示例文本 -
<h3>Post Title</h3>
<p>This is a paragraph of text of the post</p>
<img src="http://imageurl">
<p>Please read more on this link</p><br/>
http://www.readmorelink.com/1212/1212post
您使用的正则表达式似乎有误。
试试这个:
text_to_url = text_to_url.replaceAll("(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))", "<a href=\"[=10=]\">[=10=]</a>");
这个正则表达式不是我写的,它实际上是 john gruber 写的,这里有很好的解释:http://daringfireball.net/2010/07/improved_regex_for_matching_urls
您可以在各种编辑器中尝试使用正则表达式,例如这个:https://regex101.com/ - 他们非常容易理解正在发生的事情。
我发现你的正则表达式中有一个小错误。它应该是 https?
而不是 http(?s)
以使 s
可选。 (?s)
表示使 .
也匹配换行符的内联修饰符。
据
but it not stop at end of url (I think according to *)
是的,你是对的,这是因为 *
即 greedy by default。您可以通过在其后添加 ?
使其变得懒惰。
但更好的方法是使用 this
text_to_url= text_to_url.replaceAll("(?<!\")(https?://[^\s\n]*)(?!\")", "<a href=\"[=10=]\">[=10=]</a>");
其中 [^\s\n]*
将匹配任何非 space 或换行符的字符零次或多次。
我对正则表达式字符串和操作非常陌生。但是我正在尝试开发一个 android 应用程序,它需要将文本 url (没有标签)从整个字符串替换为
<a href='$link'>$link </a>
我发现工作代码 -
text_to_url= text_to_url.replaceAll("(<a[^>]+>)|(http(?s)://.*)", "<a href=\"[=14=]\">[=14=]</a>");
但正如我在上面承认的那样,我对正则表达式单词和函数非常陌生。
即使我可以使用该代码获得 url 内部标记,但它不会在 url 结束时停止(我认为根据 *)。
问题是,如果有2个或更多连续的link_text_urls并排或逐行显示为一个link(url是第一个发生 url) .
我尝试了很多次并通过谷歌搜索找到了这个结果。但是我的正则表达式知识无法帮助我找到它。
请告诉我答案。非常感谢您理解我的问题。
示例文本 -
<h3>Post Title</h3>
<p>This is a paragraph of text of the post</p>
<img src="http://imageurl">
<p>Please read more on this link</p><br/>
http://www.readmorelink.com/1212/1212post
您使用的正则表达式似乎有误。
试试这个:
text_to_url = text_to_url.replaceAll("(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))", "<a href=\"[=10=]\">[=10=]</a>");
这个正则表达式不是我写的,它实际上是 john gruber 写的,这里有很好的解释:http://daringfireball.net/2010/07/improved_regex_for_matching_urls
您可以在各种编辑器中尝试使用正则表达式,例如这个:https://regex101.com/ - 他们非常容易理解正在发生的事情。
我发现你的正则表达式中有一个小错误。它应该是 https?
而不是 http(?s)
以使 s
可选。 (?s)
表示使 .
也匹配换行符的内联修饰符。
据
but it not stop at end of url (I think according to *)
是的,你是对的,这是因为 *
即 greedy by default。您可以通过在其后添加 ?
使其变得懒惰。
但更好的方法是使用 this
text_to_url= text_to_url.replaceAll("(?<!\")(https?://[^\s\n]*)(?!\")", "<a href=\"[=10=]\">[=10=]</a>");
其中 [^\s\n]*
将匹配任何非 space 或换行符的字符零次或多次。