简体   繁体   English

C#Regex验证字符串

[英]C# Regex to validate string

I have the following regex pattern: 我有以下正则表达式模式:

"[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}"

and I want to validate a string with the following conditions 我想验证具有以下条件的字符串

  • allow only alphanumeric characters 仅允许使用字母数字字符
  • has length of only 8 or 11 长度只有8或11
  • first 6 characters must all be uppercase letters 前6个字符必须都是大写字母

However, the above pattern is not working. 但是,上述模式不起作用。 What needs to be changed? 需要改变什么?

Use following regular expression: 使用以下正则表达式:

^[A-Z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$

First 6 characters must all be uppercase letters ( ^ means that following pattern should match at the start of the string): 前6个字符必须都是大写字母( ^表示后面的模式应该在字符串的开头匹配):

^[A-Z]{6}

Now there should be 2 or 5 more alphanumeric characters; 现在应该有2或5个字母数字字符; 2 alphanumeric chracters should come anyway: 无论如何都应该有2个字母数字字符:

[A-Za-z0-9]{2}

and 3 after that is optional ( ? : 0 or 1 match of the preceding pattern, $ means that preceding pattern should match at the end of the string): 之后的3是可选的( ? :前一个模式的0或1匹配, $表示前面的模式应该在字符串的末尾匹配):

([A-Za-z0-9]{3})?$

Using ^ and $ together ( ^PATTERN$ ), the pattern should match the whole string instead of the substring. 使用^$ together( ^PATTERN$ ),模式应匹配整个字符串而不是子字符串。

表达式应该是:

^[A-Z]{6}([A-Za-z0-9]{2}|[A-Za-z0-9]{5})$

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

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