我需要一个正则表达式来执行以下操作
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/