【问题标题】:Regex to catch links with special codes正则表达式捕获带有特殊代码的链接
【发布时间】:2016-06-22 17:32:46
【问题描述】:

我有一个接近但不完全存在的正则表达式:

(https?)://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,\<\>]*)

它应该在它们被替换之前捕获带有特殊代码的链接。这是一个示例文本:

some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=<#specialcode#></a>. Some text afterwards

另一个例子:

some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=<#first#>&querystring2=<#another#>&querystring3=foo&querystring4=<#bar#></a>

甚至只是“普通”链接:

some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=foo&querystring2=bar</a>

我想捕获所有这些链接,不带标签,并且一些链接包含分隔符。

根据测试人员的说法,它很接近,但它一直在捕捉结束时的结束标签和句点。我明白为什么,我只是不知道如何解决它。在我的示例中,我需要在它之后捕获 和任意数量的其他查询字符串。没有太多细节, 是应用程序中的分隔符。如有任何帮助,我们将不胜感激。

我从这里获取了根正则表达式:Get url from a text 我在这里尝试过测试:http://www.regextester.com/

【问题讨论】:

  • bruh... 正则表达式?使用ParseQueryStringstackoverflow.com/a/6082703/940217
  • @KyleFalconer 如何从大量文本中找到并提取链接?
  • 如果您的文本是 HTML 会容易得多...
  • 我认为您实际上并没有在参数中使用未编码的# - 它是一个保留字符:Characters allowed in GET parameter
  • @AlexeiLevenkov:我猜是在等待pony :)

标签: c# regex


【解决方案1】:

假设输入文本不是正确的 HTML 文档,并且假设您只是想提取 url 和查询字符串和参数,这个正则表达式会做到:

(https?:\/\/[^?<]+)[?]?(([^=<]+)=(<#[^&<]*#>|[^&<]*)&?)*

这基于以下测试输入:

some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=<#specialcode#></a>. Some text afterwards
some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=<#specialcode#>&querystring2=foo</a>. Some text afterwards
some leading text <a>http://subsite.domain.com/somepage.aspx?querystring1=<#specialcode#>&querystring2=foo&querystring3=<#specialcode2#></a>. Some text afterwards
some leading text <a>http://subsite.domain.com/somepage.aspx</a>. Some text afterwards

结果将在捕获组中。

如果给定的文本是 HTML 文档,那么正则表达式必须更改,因为链接不是在 &lt;a&gt;http://linkhere.com&lt;/a&gt; 中,而是在 href 属性中:&lt;a href="http://linkhere.com"&gt;link here&lt;/a&gt;

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2011-02-20
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多