简体   繁体   中英

Regex to match a specific character?

I need to make a Regular expression that will match the character "N" when it is alone. So far, I've come up with the expression: "^[N]$" which seems to work in this example. It doesn't match on the other three, just the "N".

public static void Main()
{
    string[] words = new string[] { "42ND", "N", "WATERING", "ANONYMOUS"};

    string pattern = @"^[N]$";

    foreach (string word in words)
    {
        if( Regex.IsMatch(word, pattern))
        {
            Console.WriteLine(word + " Is a match"); 
        }
    }
} 

Can anyone pick out any problems with this or provide a better one? Thank you!

Edit for a little clarity: I'm just looking to match on the letter "N" and nothing more. It should not match on "NN", "NNN", or any variation and should not match on any words that contain the letter "N" .

You could use \\b (word boundary match) that way you could pick out all "single-N" words in a string (not sure if that's what you actually need, but the array of strings you have in the example suggests that might be the case).

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace ConsoleApplication1 {
    internal class Program {
        private static void Main(string[] args) {
            var pattern = new Regex(@"\bN\b");
            const string input = "N foo N bar N";
            MatchCollection matches = pattern.Matches(input);
            Debug.Assert(matches.Count == 3);
            foreach (Match m in matches) {
                Console.WriteLine(m.Value);
            }
        }
    }
}

You don't really need the character class ( [ and ] ) when it's only one character ^N$ means the same as ^[N]$ .

What your regex is matching is a string that consists of a single character: N .

^ matches the start of a string and $ the end of it the only valid character in between is N , so it will only match the string N .


Update:

If all you're after is a string consisting of N , then you don't need regex at all, as other have suggested, use if (word == "N") or if you want to get any words consisting of N out of a larger string then you'd use \\bN\\b .

如果您只是想查找与字符串"N"的完全匹配,则无需使用正则表达式!

if ( word == "N" ) ...

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