这也将捕获www.test.com
:
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?)
↑---------------------↑↑
只需将可选部分括起来并附加一个问号即可。您可以在
这里查看。
这个正则表达式中的第一个匹配项(匹配项由“(”和“)”定义)是整个URL。因此,您可以像这样使用替换:
Regex rgxUrls = new Regex(pattern);
string result = rgxUrls.Replace(yourText, "<a href=\"$1\"> space for custom text </a>");
↑ Inserts first match
![enter image description here](https://istack.dev59.com/uWKLL.webp)
当我使用$1
时,您也可以使用$2-$5
。请查看上面显示哪些组捕获了URL的哪个部分的图像。
完整测试可以在此处找到here。
只需点击顶部的执行即可。
输出:
![enter image description here](https://istack.dev59.com/K8rCH.webp)
根据评论,组标题的工作原理如下:
Text: "this is your text to search"
Pattern: "text to"
Match[0]总是匹配你的整个匹配文本
。上面的每个组,如Match[1]
或Match[2]
,都必须用“(”和“)”定义。
Text: "this is your text to search"
Pattern: "text (to)"
Match[0]: "text to"
Match[1]: "to"
Pattern: "text (t(o))"
Match[0]: "text to"
Match[1]: "to"
Match[2]: "o"
带有“()”的标题从外到内生效。
$1
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+
↑--------------------------------------------------------------------------------------------------↑
$2 (http://)
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+
↑---------------------↑
$3 (http)
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+
↑--------------↑
$4 (.com)
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+
↑----------↑
$5 (/appendedSubdirectory/anotherOne)
(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+
↑--------------------------------------------------↑
我无法在这里解释有关正则表达式的一切。对我来说,这个问题看起来已经解决了。如果您对正则表达式有更深入的问题,请开始一个新的问题,并展示一些您之前所做的努力。
www.google.de
替换为http://www.google.de
吗?我会编辑我的问题并解释组标题。 - C4d