开发者

Regex for a string of n characters

I want to use .NET'开发者_JAVA百科s Regex.IsMatch function to determine if a string is 8 characters long and matches the expression AK-\d\d\d\d[fF]. So, AK-9442F would match but not AK-9442F2 nor AK-9442. How would I construct the expression?


Using the static Regex.IsMatch, you can do:

if (Regex.IsMatch(myTestString, @"^AK-\d{4}[fF]$")) {
  // passed
}

Should work for your purpose. Broken down, it's:

^       # must match beginning of the string
  AK-     # string literal, "AK-"
  \d{4}   # \d is digit, {4} means must be repeated 4 times
  [fF]    # either upper or lowercase F
$       # must match end of string

GSkinner Test


Use this pattern: ^AK-\d{4}[Ff]$

The ^ matches the beginning of the string, and $ matches the end of the string. This ensures that the entire string must match and avoids any partial matches. The \d{4} matches exactly 4 digits.

string pattern = @"^AK-\d{4}[Ff]$";
bool result = Regex.IsMatch("AK-1234F", pattern);
Console.WriteLine(result);


 Regex.IsMatch(myString, @"^AK-\d{4}[fF]$")


You alread have it.

Something like this should work:

^AK-[0-9]{4}[Ff]$

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜