2012-11-30 130 views
6

我需要在C#中使用正则表达式在下列条件下匹配的字符串:C#正则表达式匹配15个字符,一个空格,字母数字

  1. 整个字符串只能是字母(包括空格)。
  2. 最多不能超过15个字符(包括空格)。
  3. 第一个&最后的字符只能是一个字母。
  4. 单个空格可以在除字符串的第一个和最后一个字符之外的任何地方出现多次。 (不应允许多个空间在一起)。
  5. 大写应忽略。
  6. 应匹配整个单词。

如果这些先决条件中的任何一个被破坏,则不应遵循匹配。

这里是我目前有:

^\b([A-z]{1})(([A-z0-9 ])*([A-z]{1}))?\b$ 

这里有一些应该匹配测试字符串:

  • 堆栈溢出
  • Iamthe最大
  • 一个
  • superman23s
  • One Two Thr ee值

有的认为不应该匹配(注意空格):

  • 堆栈[double_space]溢出岩石
  • 23Hello
  • ThisIsOver15CharactersLong
  • Hello23
  • [space_here]嘿

任何建议将不胜感激。

+0

您的正则表达式有什么问题? –

+0

问题是当我只想匹配一个空格时,它匹配双空格。我分享所有不相关的细节的唯一原因是因为我不希望我的可能不正确的正则表达式负担其他人试图匹配我设定的条件。 – user1684699

+0

你的第一个字符串是如何匹配的?它超过15个字符 –

回答

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

+4

啊,旧的多重前瞻 - 匹配 - 多重条件技巧。 (“老”,我的意思是“我在过去48小时内了解到这一点”)非常好,虽然第一个前瞻需要至少两个字符 – Rawling

+0

@Rawling ahh..nice观察..改正它 – Anirudha

+1

这允许最后的字符成为一个数字 - OP状态最后字符只能是一个字母 – garyh

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 

更新: -

为了处理单个字符,可以使第1个字符可选的,通过很好的@Rawling评论中指出后的图案: -

"^([a-zA-Z](([ ](?=[a-zA-Z0-9])|[a-zA-Z0-9]){0,13}[a-zA-Z])?)$" 
     ^^^           ^^^ 
    use a capture group       make it optional 
+0

非常好,虽然这又要求至少两个输入中的字符,并进一步将最后一个字符限制为字母而不是字母或数字。 – Rawling

+0

@Rawling ..我认为OP不希望最后一个字符是来自这个字符串的'digit' - 'Hello23'。他不想与此相匹配。但是,它可以被修改。 –

+0

@Rawling。为了您的首要关注,我需要看看修改。请稍候。 –

0

而且我的版本,再次使用look- aheads:

^(?=.{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选项设置

+0

'(?![] {2}'应该是'(?!。* [] {2}' – Anirudha

相关问题