Search code examples
c#regexletters

How to structure REGEX in C#


I currently have a regex that checks if a US State is spelled correctly
var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters. ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.


Solution

  • It seems you need start of string (^) and end of string ($) anchors:

    var r = new Regex(string.Format(@"^(?:{0})$", pattern), RegexOptions.IgnoreCase);
    

    The regex above would match any string comprising a name of a state only.