Подтвердить что ты не робот

С# regex pattern для извлечения URL-адресов из заданной строки - не полный URL-адрес html, но также и ссылки

Мне нужно регулярное выражение, которое будет делать следующее

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

Поэтому мне нужно извлечь эти 2.

Например, приведенный ниже текст строки ниже

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

Поиск регулярного выражения или другим способом. Спасибо.

С# 4.0

4b9b3361

Ответ 1

Вы можете написать несколько простых регулярных выражений, чтобы справиться с этим, или использовать более традиционное разделение строк + методология LINQ.

Regex

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\.) 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);