user34537
user34537

Reputation:

Is there Match Or Exception Regex in .NET

I would like to do something like the below but throw an exception because there is no match. Is that possible?

var val = Regex.Match("nomatchplz", "notgoingtomatch(.*)").Groups[1].Value;

Upvotes: 2

Views: 2601

Answers (3)

Ari Roth
Ari Roth

Reputation: 5534

The easiest way is to check the result of the regex and throw if no matches are found. Unless I'm misunderstanding?

Upvotes: 0

Sjuul Janssen
Sjuul Janssen

Reputation: 1812

The Regex.Match function returns a Match object. It has the functionality you're looking for. But you should throw the exception yourself

    Match x = Regex.Match("","");
    if (!x.Success)
    {
        throw new Exception("My message");
    }

Upvotes: 7

Michael Stum
Michael Stum

Reputation: 181044

Doesn't .Value already throw a NullReferenceException because Group[1] is false? Or is Group[1] already cause an ArgumentOutOfRangeException because the Indexer can't be resolved?

Upvotes: 1

Related Questions