【问题标题】:Reg expression in .net to start with 2 specific characters, end with a digit, and at a certain length.net 中的正则表达式以 2 个特定字符开头,以数字结尾,并以一定长度
【发布时间】:2019-05-28 14:56:41
【问题描述】:

Ok Reg ex 专家,我不太擅长正则表达式,希望能得到一些帮助。我有一个正则表达式,我一生都无法弄清楚。我希望创建一个匹配以下内容的正则表达式:

以“PA”开头(ingore 大小写)

以数字结尾

长度为 8 个字符(忽略任何尾随空格)

以“WN”开头(ingore 大小写)

以数字结尾

长度为 10 个字符(忽略任何尾随空格)

【问题讨论】:

  • 说实话我什至不知道从哪里开始

标签: .net regex


【解决方案1】:
//Trim the whitespace off the ends of your string per requirement
yourString = yourString.Trim();
//Declare regex, the pattern tells it to look for any 7 letter word
//which starts with PA and ends with a digit and is 7 characters long
//OR a word which starts with WN and ends with a digit and is 10 characters long. 
Regex regex = new Regex(^PA.+\d${7})|(^WN.+\d${10});
//Set the regex option to ignore case
RegexOptions options = RegexOptions.IgnoreCase;
//Get the match collection by passing your string, the regex pattern and
//the regex options
MatchCollection matches = regex.Matches(yourString, regex, options);

//Do something with captured text

【讨论】:

  • @d_kennetz 您好,感谢您让我知道答案被标记。我添加了很多 cmets 来解释我的答案,如果您需要我的任何其他内容,请告诉我。
  • 感谢您的回答!我唯一的问题是这将在 MVC 数据属性中使用,因此 .IgnoreCase 是不可能的。我很抱歉。我应该更具体。我想我可以添加另一个或使用小写版本
  • @JSON 只需注释掉RegexOptions.IgnoreCase 行,并在第一行修剪空白处,也调用ToLower(),所以yourString = yourString.ToLower().Trim(); 而且,欢迎您回答,我希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 2017-09-17
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 2023-01-02
  • 1970-01-01
相关资源
最近更新 更多