私は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に相当するものもあると思います。