6

C#で正規表現を使用して次の条件下で文字列を照合する必要があります。

  1. 文字列全体は英数字(スペースを含む)のみにすることができます。
  2. 最大15文字以下(スペースを含む)である必要があります。
  3. 最初と最後の文字は文字のみにすることができます。
  4. 1つのスペースは、文字列の最初と最後の文字以外の場所に複数回出現する可能性があります。(複数のスペースを一緒に使用することはできません)。
  5. キャピタライゼーションは無視する必要があります。
  6. 単語全体と一致する必要があります。

これらの前提条件のいずれかが破られた場合、一致は続きません。

これが私が現在持っているものです:

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

そして、これが一致するはずのいくつかのテスト文字列です:

  • スタックオーバーフロー
  • Iamthe最大
  • A
  • superman23s
  • 一二三

そして、一致してはならないものもあります(スペースに注意してください):

  • スタック[double_space]オーバーフローロック
  • 23こんにちは
  • ThisIsOver15CharactersLong
  • Hello23
  • [space_here]ねえ

任意の提案をいただければ幸いです。

4

3 に答える 3

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

ここで試すことができます

于 2012-11-30T10:31:16.253 に答える
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
于 2012-11-30T10:47:09.150 に答える
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オプション設定も必要です。

于 2012-11-30T11:34:29.793 に答える