2017-08-27 80 views
-1

我目前正試圖在字符串上運行兩個不同的正則表達式模式,以比較字符串是使用C#的myspace.com還是last.fm url。檢查多個正則表達式模式的字符串

我得到它的工作使用單一的正則表達式用下面的代碼:

public string check(string value) 
{ 
    Regex DescRegexShortened = new Regex(@"myspace\.com\/([a-zA-Z0-9_-]*)"); 
    Match DescRegexShortenedMatch = DescRegexShortened.Match(value); 

    string url = ""; 

    if (DescRegexShortenedMatch.Success) 
    { 
     url = DescRegexShortenedMatch.Value; 
    } 

    return url; 
} 

現在我的問題,是有simplier方法來檢查,如果字符串或者是myspace.com或last.fm網址?

Regex DescRegexShortened = new Regex(@"myspace\.com\/([a-zA-Z0-9_-]*)"); 
Regex mySpaceRegex = new Regex(@"last\.fm\/([a-zA-Z0-9_-]*)"); 

例如像:

如果字符串匹配regex1的或regex2然後...

+0

看起來你只關心last.fm或myspace.com,而不是在那之後。你不只是做一個字符串.StartsWith或string.Contains而不是正則表達式模式?或者你的情況通常需要正則表達式嗎? –

+0

您的正則表達式在'myspace.com?a = b'上失敗。邁克爾是正確的。 – linden2015

+0

我目前正在嚮應用程序上傳一個包含用戶名的文本文檔。現在應用程序將使用API​​來接收Twitter用戶的生物和網站。現在,每個站點都將被添加到C#列表中,並且將通過這兩個正則表達式模式運行,這些模式檢查url是myspace還是last.fm url因此,它後面的用戶名並不重要 – stackquestiionx

回答

1

也許這是太明顯了:

var rx1 = new Regex(@"myspace\.com\/([a-zA-Z0-9_-]*)"); 
var rx2 = new Regex(@"last\.fm\/([a-zA-Z0-9_-]*)"); 

if (rx1.IsMatch(value) || rx2.IsMatch(value)) 
{ 
    // Do something. 
} 
0

您可以在常規使用交替表達式來檢查不同的值而不是檢查多個正則表達式:

var regex = new Regex(@"(?<domain>myspace\.com|last\.fm)/[a-zA-Z0-9_-]*"); 
var match = regex.Match(value); 
if (match.Success) 
{ 
    var domain = match.Groups["domain"].Value; 
    // ... 
} 
else 
{ 
    // No match 
} 

在這種情況下,更改爲myspace\.com|last\.fm,它與myspace.comlast.fm相匹配。交替位於名爲domain的組中,如果正則表達式匹配,則可以像我在代碼中那樣訪問此已命名組的值。

而不是使用正則表達式,你可能只是檢查字符串或者myspace.comlast.fm開始,或者如果URL的是真實的URL使用正確的語法像http://myspace.com/bla您可以創建和Uri類的實例,然後檢查Host財產。

如果你想使用正則表達式,你應該改變它不匹配域如fakemyspace.com,但仍然匹配MYSPACE.COM

+0

開始時的單詞邊界在這裏使用正則表達式是一個更好的藉口。 –

相關問題