有人可以建议吗?全部替换方法是如何工作的?
message = message.replaceAll("(?:https?|http?)://[\\w/%.\\-?&=!#]+",
"<a href='$0' target='_blank'>$0</a>");
最佳答案
您应该一次完成每个步骤,以了解:
(?:https?|http?)
|
-> 表示 OR,因此表示匹配 https 或 http
?
-> (仅在这里)表示可选元素,来自 https 的“s”是可选的,或者来自 http 的“p”也是可选的。您可能的意思是:“(https)?|(http)?
”,使每个选项可选。但这仍然是错误的,因为您可以匹配这样的字符串:“://someLink
” - 这是没有意义的。
我想你想匹配 https 或 http,因此你的正则表达式需要更改为:
https? (to make only the s optinal)
?:
-> 它定义了一个非捕获组(这意味着它将被匹配但不会出现在输出中 - 不会在结果中捕获),这与正则表达式组相关。
()
-> 表示这是一个组
事实上,这是第二组(第一组是整场比赛本身)
这个正则表达式“://[\\w/%.\\-?&=!#]+
”我认为上面已经解释得很好了。
这里发生的“魔法”是:“$0
”,这称为对匹配组的反向引用。因此,在您的消息字符串中,您与正则表达式匹配的结果:
(?:https?|http?)://[\\w/%.\\-?&=!#]+
将替换为:
"<a href='$0' target='_blank'>$0</a>"
其中 $0
实际上是使用第一个正则表达式找到的内容。
这是一个实际的例子:
// I've simplified: \\w+ any number of characters
String regex = "https?://\\w+";
String input = "http://value1 ; https://value2";
input = input.replaceAll(regex, "<a href='$0' target='_blank'>$0</a> ");
// this will output :
// <a href='http://value1' target='_blank'>http://value1</a> ; <a href='https://value2' target='_blank'>https://value2</a>
System.out.println(input);
关于javascript - 这个正则表达式是什么意思。检查 http 或 https 超链接就足够了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9139511/