【问题标题】:Regular Expression - detect Specific Url and replace that string正则表达式 - 检测特定 URL 并替换该字符串
【发布时间】:2016-06-20 08:23:12
【问题描述】:

我想在字符串中检测确切的域url,然后用另一个字符串更改它,最后使它在TextView 中可点击。

我想要什么:

this is sample text with one type of url mydomain.com/pin/123456. another type of url is mydomain.com/username.

好吧,我写了这个正则表达式:

([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/?.*

([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/pin/?.*

这个正则表达式可以检测到:

http://www.example.com
https://www.example.com
www.example.com
example.com
Hhtp://www.example.com // and all other wrong type in http

.com 之后的任何内容

问题:

1.如何检测域的结尾(带空格或点)

2.如何检测两种类型的域,一种带有/pin/,另一种没有?

3. 如何用PostLinkmydomain.com/usernameProfileLink 替换检测到的域,如mydomain.com/pin/123ProfileLink

4.我知道如何使用Linkify 使它们可点击,但如果可能的话,请向我展示为链接提供内容提供商的最佳方式,以通过适当的活动打开每个链接

【问题讨论】:

  • 那你为什么不使用Linkify
  • @pskink 怎么样?你能提供sn-p的代码吗
  • I know how to make them clickable with Linkify,如果你知道你需要什么代码?
  • @pskink 问题是regex 未链接
  • 您的网址总是包含 http/https 还是总是像您的示例一样?也总是 1 或 2 个 2 斜线还是可以更多?

标签: java android regex linkify


【解决方案1】:

你可以试试:

([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?

这是我在 stackoverflow 上快速搜索后发现的一个正则表达式:
Regular expression to find URLs within a string

我刚刚删除了该正则表达式的 http:// 部分以满足您的需求。

请注意,因为它现在会跟踪与点相连且没有空格的所有内容。例如:a.a 也会被发现

【讨论】:

  • 老兄,首先我想在字符串中检测 specific domain url 而不是 all url。正如我在问题描述中所说的那样,我发现我想用另一个字符串替换它们并最终通过Linkify 使其可点击。感谢您的关注;)
  • @MAY3AM demo.com+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])? 将为您提供与域 demo.com 匹配的所有字符串。如果 pin 总是在同一个位置:demo.com\/pin+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])? 然后我会比较两个结果,因为正则表达式不擅长排除结果
【解决方案2】:

特别感谢Gildraths

问题 1 的答案

String urlRegex = "(https?://)?(?:www\\.)?exampl.com+([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textString);

回答问题 2、3

while(matcher.find()){

    // Answer to question 2 - If was true, url contain "/pin"
    boolean contain = matcher.group().indexOf("/pin/") >= 0;

    if(contain){

        String profileId = matcher.group().substring(matcher.group().indexOf("/pin/") + 5, matcher.group().length());

    }

    // Answer to question 3 - replace match group with custom text
    textString = textString.replace(matcher.group(), "@" + profileId);
}

问题 4 的答案

// Pattern to detect replaced custom text
Pattern profileLink     = Pattern.compile("[@]+[A-Za-z0-9-_]+\\b");

// Schema
String Link             = "content://"+Context.getString(R.string.profile_authority)+"/";

// Make it linkify ;)
Linkify.addLinks(textView, profileLink, Link);

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多