android - 在 Android 中读取自定义 HTML 标签并创建链接

标签 android regex hyperlink

我像这样从服务器获取文本:

sample text [myurl]link|http://sample.com[/myurl] and [myurl]link2|http://sample2.com[/myurl].

我需要从这些标签创建链接。我该怎么做?

最佳答案

我猜你需要使用这样的东西:

String s = "sample text [myurl]link|http://sample.com[/myurl]";
System.out.println(s.replaceAll("\\[([^\\]]+)\\]([^|]+)\\|(http.+?)\\[/\\1\\]", "<a href=\"$3\">$2</a>"));

参见 IDEONE demo

正则表达式:

  • \[ - 文字 [
  • ([^\]]+) - ] 以外的 1 个或多个字符
  • \] - 文字 ]
  • ([^|]+) - |
  • 以外的 1 个或多个字符
  • \| - 文字 |
  • (http.+?) - 以 http 开头的子字符串,然后是除新字符之外的任何字符,直到...
  • \[/ - 文字 [/
  • \1 - 对第一组捕获的文本的反向引用(BB 标签名称)
  • \] - 文字 ]

输出:

sample text <a href="http://sample.com">link</a>

关于android - 在 Android 中读取自定义 HTML 标签并创建链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136427/

相关文章:

android - 用户获取未包含在 list 中的权限请求

android - 一个 BroadcastReceiver 可以用于多个 IntentServices 吗?

regex - Golang 正则表达式匹配 +-/*

regex - 提取以 &[? 开头的最后一个元素的正则表达式

regex - Dart 捕获replaceAll 中的括号

java - 如何删除显示应用程序名称的标题而不是标题栏本身?

java - LocalBroadcastManager、冗余 Activity 、 Activity 生命周期

html - 链接以两个斜杠开头

iphone - 在 iPhone 中显示超链接

javascript - 将事件类添加到当前元素