stackquestiionx
stackquestiionx

Reputation: 21

Check a string for multiple regex pattern

I'm currently trying to run two different regex patterns on a string to compare if the string is a myspace.com or a last.fm url using C#.

I got it working using a single regex with the following code:

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;
}

Now my question, is there a simplier way to check if the string is either a myspace.com or a last.fm url?

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

for example something like:

if string matches regex1 or regex2 then ...

Upvotes: 0

Views: 4892

Answers (2)

Martin Liversage
Martin Liversage

Reputation: 106826

You can use alternation in a regular expression to check for different values instead of checking multiple regular expressions:

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
}

In this case the alternation is myspace\.com|last\.fm which matches either myspace.com or last.fm. The alternation is inside a named group domain and if the regular expressions matches you can access the value of the this named group as I do in the code.

Instead of using regular expressions you might just check if the string starts with either myspace.com or last.fm or if the URL's are real URL's using proper syntax like http://myspace.com/bla you can create and instance of the Uri class and then check the Host property.

If you want to use regular expressions you should probably change it to not match domains like fakemyspace.com but still match MYSPACE.COM.

Upvotes: 0

Uwe Keim
Uwe Keim

Reputation: 40736

Probably this is too obvious:

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.
}

Upvotes: 2

Related Questions