接受的例子:
This is a try! And this is the second line!
示例不被接受:
this is a try with initial spaces and this the second line
所以,我需要:
我正在使用
^(?=\s*\S).*$
但该模式不允许新行。
答案 0 :(得分:2)
你可以试试这个正则表达式
^(?!\s*$|\s).*$
---- -- --
| | |->matches everything!
| |->no string where first char is whitespace
|->no string made only by whitespaces
您需要使用singleline
模式..
你可以尝试here ..你需要使用matches
方法
答案 1 :(得分:2)
“仅由空格构成的字符串”与“第一个字符为空格的字符串”相同,因为它也以空格开头。
你必须设置Pattern.MULTILINE
来改变^和$的含义也可以改为开头和结尾,而不仅仅是整个字符串
"^\\S.+$"
答案 2 :(得分: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也有相同的东西。