我需要在C#中使用Regex在以下条件下匹配字符串:
如果这些先决条件中的任何一个被打破,则不应该进行匹配。
以下是我目前的情况:
^\b([A-z]{1})(([A-z0-9 ])*([A-z]{1}))?\b$
以下是一些应该匹配的测试字符串:
有些不应该匹配(注意空格):
等
我们非常感谢任何建议。
答案 0 :(得分:5)
您应该使用lookaheads
|->matches if all the lookaheads are true
--
^(?=[a-zA-Z]([a-zA-Z\d\s]+[a-zA-Z])?$)(?=.{1,15}$)(?!.*\s{2,}).*$
-------------------------------------- ---------- ----------
| | |->checks if there are no two or more space occuring
| |->checks if the string is between 1 to 15 chars
|->checks if the string starts with alphabet followed by 1 to many requireds chars and that ends with a char that is not space
你可以尝试here
答案 1 :(得分:3)
试试这个正则表达式: -
"^([a-zA-Z]([ ](?=[a-zA-Z0-9])|[a-zA-Z0-9]){0,13}[a-zA-Z])$"
说明: -
[a-zA-Z] // Match first character letter
( // Capture group
[ ](?=[a-zA-Z0-9]) // Match either a `space followed by non-whitespace` (Avoid double space, but accept single whitespace)
| // or
[a-zA-Z0-9] // just `non-whitespace` characters
){0,13} // from `0 to 13` character in length
[a-zA-Z] // Match last character letter
更新: -
要处理单个字符,您可以在注释中@Rawling
指向第一个字符后选择第一个字符后的模式: -
"^([a-zA-Z](([ ](?=[a-zA-Z0-9])|[a-zA-Z0-9]){0,13}[a-zA-Z])?)$"
^^^ ^^^
use a capture group make it optional
答案 2 :(得分:0)
我的版本,再次使用预见:
^(?=.{1,15}$)(?=^[A-Z].*)(?=.*[A-Z]$)(?![ ]{2})[A-Z0-9 ]+$
说明:
^ start of string
(?=.{1,15}$) positive look-ahead: must be between 1 and 15 chars
(?=^[A-Z].*) positive look-ahead: initial char must be alpha
(?=.*[A-Z]$) positive look-ahead: last char must be alpha
(?![ ]{2}) negative look-ahead: string mustn't contain 2 or more consecutive spaces
[A-Z0-9 ]+ if all the look-aheads agree, select only alpha-numeric chars + space
$ end of string
这也需要IgnoreCase选项设置