简体   繁体   中英

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?

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM