0

受け入れられた例:

This is a try!
And this is the second line!

受け入れられない例:

      this is a try with initial spaces
and this the second line

だから、私は必要です:

  • 空白だけで作られた文字列はありません""
  • 最初の文字が空白である文字列はありません
  • 新しい行は大丈夫です。最初の文字だけを改行することはできません

使っていた

^(?=\s*\S).*$

しかし、そのパターンでは新しい行を許可できません。

4

3 に答える 3

2

「空白だけで作成された文字列なし」は、「最初の文字が空白である文字列なし」と同じです。これも空白で始まるためです。

Pattern.MULTILINE文字列全体だけでなく、行の先頭と末尾にも^と$の意味を変更するものを設定する必要があります

"^\\S.+$"
于 2013-01-05T13:49:42.230 に答える
2

この正規表現を試すことができます

^(?!\s*$|\s).*$
    ---- -- --
      |   |  |->matches everything!
      |   |->no string where first char is whitespace
      |->no string made only by whitespaces

singlelineモードを使用する必要があります。


ここで試すことができます..matchesメソッドを使用する必要があります

于 2013-01-05T13:43:44.733 に答える
0

私はJavaの人ではありませんが、Pythonのソリューションは次のようになります。

In [1]: import re

In [2]: example_accepted = 'This is a try!\nAnd this is the second line!'

In [3]: example_not_accepted = '   This is a try with initial spaces\nand this the second line'

In [4]: pattern = re.compile(r"""
  ....:     ^     # matches at the beginning of a string
  ....:     \S    # matches any non-whitespace character
  ....:     .+    # matches one or more arbitrary characters
  ....:     $     # matches at the end of a string
  ....:     """,
  ....:     flags=re.MULTILINE|re.VERBOSE)

In [5]: pattern.findall(example_accepted)
Out[5]: ['This is a try!', 'And this is the second line!']

In [6]: pattern.findall(example_not_accepted)
Out[6]: ['and this the second line']

ここで重要なのは旗re.MULTILINEです。このフラグを有効にする^$、文字列の最初と最後だけでなく、改行で区切られた行の最初と最後でも一致します。Javaに相当するものもあると思います。

于 2013-01-05T14:20:46.080 に答える