richzilla
richzilla

Reputation: 41982

Match single character in .net regex

According to the MSDN documentation, the . character

Matches any single character except \n.

In this case, why does this regex not match?:

Regex.IsMatch("c",@"[.]")

Upvotes: 5

Views: 5790

Answers (4)

vks
vks

Reputation: 67968

You are matching [.] which means character .. Use just . to get your result. The [] mean any of the character inside. So by . loses its special meaning because of this.

See demo.

http://regex101.com/r/qC9cH4/19

c is being captured by the second group, not the first one.

Upvotes: 7

Margus
Margus

Reputation: 20038

You can just use:

Console.WriteLine(Regex.IsMatch("c", @"."));

If you do this often, then add

public static class Extensions
{
    public static bool Match(this string value, String query)
    {
        return Regex.IsMatch(value, query);
    }

    public static void Out<t>(this t value)
    {
        Console.WriteLine(value);
    }
}

After that you can use

"c".Match(".").Out();

Upvotes: 1

Jeffrey Wieder
Jeffrey Wieder

Reputation: 2376

You cannot use . inside [] to get all characters. Remove the [] and it will work.

Upvotes: 1

user4079229
user4079229

Reputation:

Replace @"[.]"; with @"."; // Use .

Upvotes: 1

Related Questions