简体   繁体   中英

C# regex match, match.Success returns false even after following the rules

Friends, I want to match a string like "int lnum[];" so I am trying to match it with a pattern like this

[A-Za-z_0-9] [A-Za-z_0-9]\[\] 

but it does not seem to work. I looked up rules at http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

string pJavaLine = "int lnum[]";
match = Regex.Match(pJavaLine, @"[A-Za-z_0-9] [A-Za-z_0-9]\[\] ", RegexOptions.IgnoreCase);
            if (match.Success) {
                // Finally, we get the Group value and display it.
                string key = match.Groups[1].Value;
                Console.WriteLine(key);
            }

the match.Success returns false. Would anybody please let me know a possible way to get this.

Each of your character classes, like [A-Za-z_0-9] , matches only a single character. If you want to match more than one character, you need to add something to the end. For example, [A-Za-z_0-9]+ -- the + means 1 or more of these. You could also use * for 0 or more, or specify a range, like {2,5} for 2-5 characters.

That said, you can use this pattern to match that string:

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

The \\w is loosely equivalent to [A-Za-z_0-9] (see link in jessehouwing's comment below), so you can probably simply use:

\w+ \w+\[\]

Check here for more info on the standard Character Classes .

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