简体   繁体   English

用于检查字符串是否以],字母和数字开头的正则表达式模式

[英]Regex pattern for checking if a string starts with ], a letter and a number

I'm developing a library with .NET Framework 4.0 and C#. 我正在使用.NET Framework 4.0和C#开发一个库。

I want to check if a string begins with this three caracters: 我想检查字符串是否以这三个角色开头:

  • ] ]
  • One letter (any) 一个字母(任意)
  • One number (any) 一个号码(任意)

An example: ]d2 例如: ]d2

How can I do it using regex? 我如何使用正则表达式呢?

This regex matches such a string 这个正则表达式匹配这样的字符串

^\][a-zA-Z][0-9]
  • ^ matches start of string ^匹配字符串的开头
  • ] is a special character in regex and needs to be escaped ]是正则表达式中的特殊字符,需要转义
  • [a-zA-Z] matches any letter (any case) [a-zA-Z]匹配任何字母(任何情况下)
  • [0-9] matches a digit. [0-9]匹配一个数字。 This can be replaced with \\d . 可以用\\d代替。 It is worth noting that \\d matches digits other than 0 to 9 (like Unicode values corresponding to numerals in other languages) 值得注意的是\\d匹配0到9以外的数字(例如与其他语言中的数字对应的Unicode值)
  • ^ - beginning of line ^ -行首
  • \\] - the literal character, "]" \\] -文字字符“]”
  • [a-zA-Z] - one letter, az, lower or uppercase [a-zA-Z] -一个字母,az,小写或大写
  • \\d - one digit \\d一位数字

All together: ^\\][a-zA-Z]\\d 总计: ^\\][a-zA-Z]\\d

I might be slightly off if .NET 4.0 C# regexes aren't exactly as I remember. 如果.NET 4.0 C#正则表达式与我所记得的不完全相同,我可能会稍微偏离。

在C#中,代码为:

var result = Regex.Match("]d2", @"^\][a-zA-Z][0-9].*");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM