2017-08-27 139 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

开始时的单词边界在这里使用正则表达式是一个更好的借口。 –

相关问题