从给定字符串中提取 url 的 C# 正则表达式模式 - 不是完整的 html url,而是裸链接

标签 c# regex url hyperlink extract

我需要一个正则表达式来执行以下操作

Extract all strings which starts with http://
Extract all strings which starts with www.

所以我需要提取这两个。

例如下面有这个给定的字符串文本

house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue

所以从上面给出的字符串我会得到

    www.monstermmorpg.com
http://www.monstermmorpg.com
http://www.monstermmorpg.commerged

寻找正则表达式或其他方式。谢谢。

C# 4.0

最佳答案

您可以编写一些非常简单的正则表达式来处理这个问题,或者通过更传统的字符串拆分 + LINQ 方法。

正则表达式

var linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue";
foreach(Match m in linkParser.Matches(rawString))
    MessageBox.Show(m.Value);

解释 图案:

\b       -matches a word boundary (spaces, periods..etc)
(?:      -define the beginning of a group, the ?: specifies not to capture the data within this group.
https?://  - Match http or https (the '?' after the "s" makes it optional)
|        -OR
www\.    -literal string, match www. (the \. means a literal ".")
)        -end group
\S+      -match a series of non-whitespace characters.
\b       -match the closing word boundary.

基本上,该模式会查找以 http://OR https://OR www 开头的字符串。 (?:https?://|www\.) 然后匹配所有字符直到下一个空格。

传统字符串选项

var rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue";
var links = rawString.Split("\t\n ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Where(s => s.StartsWith("http://") || s.StartsWith("www.") || s.StartsWith("https://"));
foreach (string s in links)
    MessageBox.Show(s);

关于从给定字符串中提取 url 的 C# 正则表达式模式 - 不是完整的 html url,而是裸链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10576686/

相关文章:

c# - 预加载多对多 - EF Core

c# - 如何使用 BindingSource 在 DataGridView 中绑定(bind)导航属性(二级属性)?

c# - ASP.NET c# 在每次单击按钮时按天数增加日期值

php - 如何从还包含整数的字符串中仅提取 float (小数)

php - 如何在 PHP 中将逗号和 "and"与 preg_split 匹配

javascript - Chrome 扩展程序在 # 后无法识别部分 URL(contentscript.js 匹配)

c# - 克服从 Winforms 迁移到 WPF 的更大障碍是什么?

正则表达式 - 带有空格和特殊字符

jquery - 在 jquery 插件中使用相对 API Url 的最佳方法

css - 使用 css 的 url 幻灯片