Java 正则表达式-检测特定Url并替换该字符串
我想检测字符串中的确切域Java 正则表达式-检测特定Url并替换该字符串,java,android,regex,linkify,Java,Android,Regex,Linkify,我想检测字符串中的确切域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
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.如何用PostLink
替换检测到的域,如mydomain.com/pin/123
,用ProfileLink
4.我知道如何使用Linkify
使其可点击,但如果可能,请向我展示为链接提供内容提供商的最佳方式,以便通过适当的活动打开每个链接您可以尝试:
([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
这是我在stackoverflow上快速搜索后发现的正则表达式:我刚刚删除了该正则表达式的
http://
部分,以满足您的需要
请注意,正因为如此,它现在跟踪所有与点连接的内容,而不是空白。例如:a.a
也可以找到,特别感谢
对问题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);
那么你为什么不使用
Linkify
?@pskink怎么用?你能提供一段代码吗?我知道如何使用Linkify使它们可点击,如果你知道的话,你需要什么代码?@pskink的问题是regex
不是Linkify你的URL总是包含http/https还是总是像你的例子一样?另外,它总是1或2个斜杠,还是可能更大?伙计,首先我想检测字符串中的特定域url
而不是所有url
。第二次,我发现我想用另一个字符串替换它们,正如我在问题描述中所说的,并最终通过Linkify
使其可点击。感谢您的关注;)@五月三日上午demo.com+([\w,@?^=%&:/~+-]*[\w@?^=%&/~+-])?
将为您提供与域demo.com匹配的所有字符串。如果pin总是在同一个位置:demo.com\/pin+([\w,@?^=%&:/~+-]*[\w@?^=%&/~+-])?
我会比较这两个结果,因为正则表达式不擅长排除结果