views:

62

answers:

3

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;
A: 

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?

Michael Stum
Bizarrely, no. "If groupnum is not the index of a member of the collection, or if groupnum is the index of a capturing group that has not been matched in the input string, the method returns a Group object whose Group.Success property is false and whose Group.Value property is String.Empty."
Matthew Flaschen
Thats what i would like but it returns "" if the match doesnt exist. Regardless of success or not. I wouldnt mind so much if an exception was thrown on pattern failure. Matthew +1
acidzombie24
answer is no such thing.
acidzombie24
@acid, why did you accept this? It's not correct. I would accept Sjuul's.
Matthew Flaschen
Sjuul told me what i already knew. I wanted a one line function call. I accepted this because reading any of the first two comment says no, it doesnt and you cant. -edit- also i upvoted the comment instead of the answer.
acidzombie24
+6  A: 

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");
    }
Sjuul Janssen
A: 

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

Ari Roth