Kassem
Kassem

Reputation: 8276

Get the matches of a pattern in a string

I have the following regular expression:

^[[][A-Za-z_1-9]+[\]]$

I want to be able to get all the matches of this regular expression in a string. The match should be of the form [Whatever]. Inside the braces, there could also be an _ or numeric characters. So I wrote the following code:

private const String REGEX = @"^[[][A-Za-z_1-9]+[\]]$"; 

static void Main(string[] args)
{
    String expression = "([ColumnName] * 500) / ([AnotherColumn] - 50)";

    MatchCollection matches = Regex.Matches(expression, REGEX);

    foreach (Match match in matches)
    {
        Console.WriteLine(match.Value);
    }

    Console.ReadLine();
}

But unfortunately, matches is always having a count of zero. Apparently, the regular expression is checking whether the whole String is a match and not getting the matches out of the string. I'm not sure whether the regular expression is wrong or the way I'm using Regex.Matches() is incorrect.

Any thoughts?

Upvotes: 1

Views: 109

Answers (2)

verdesmarald
verdesmarald

Reputation: 11866

You need to remove the start/end of string anchors (^ and $) from your pattern, since the matches you are looking for are not actually at the start and end of the string. You can also just use \[ and \] instead of [[] and [\]]:

private const String REGEX = @"\[[A-Za-z_1-9]+\]";

Should do the trick.

Upvotes: 6

Rudi Visser
Rudi Visser

Reputation: 22029

You're anchoring your regex to the beginning and end of the string so of course it won't match anything.

Removing the anchors (^ for beginning and $ for end) works fine:

[[][A-Za-z_1-9]+[\]]

It returns, as you would hopefully expect:

[ColumnName]
[AnotherColumn]

Upvotes: 6

Related Questions