C sharper
C sharper

Reputation: 104

Regex.IsMatch doesn't work as expected

I want that the code: Regex.IsMatch(val.ToString(),"[{()}]") will return true each time the value is a Brackets of those kinds. the code does work on those Brackets - {()} but not on those - [] .

why is that and how can I fix it? also - when I try to fix it and to reposition the Brackets like this "{([])}" it threw me an exception - why is the Brackets position matters and how does it effect the code?

Upvotes: 0

Views: 857

Answers (2)

Tomalak
Tomalak

Reputation: 338228

This can be solved by a simpler (and faster, if that matters) approach than regular expression.

Hard-coded range of characters:

switch (val.ToString()) {
    case "{":
    case "}":
    case "(":
    case ")":
    case "[":
    case "]":
        // match!
        break;
}

configurable range of characters:

var chars = "[]{}()".ToCharArray();
var str = val.ToString();

if (str.Length == 1 && str.IndexOfAny(chars) == 0) {
    // match!
}

MSDN: String.IndexOfAny Method

Upvotes: 1

Richard Szalay
Richard Szalay

Reputation: 84754

[...] matches against a set of characters, but doesn't include [] since they are part of the syntax. What you want is:

Regex.IsMatch(val.ToString(),@"[\[{()}\]]")

Since it also includes [ and ] (escaped)

(To be clear: the above syntax matches a string that contains any of those characters. It doesn't make sure it includes the appropriate opening/closing character)

Upvotes: 2

Related Questions