有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

第一个位置没有空格的java正则表达式

接受的例子:

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

不接受的示例:

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

所以,我需要:

  • 没有仅由空格“”生成的字符串
  • 没有第一个字符为空白的字符串
  • 新台词还可以;只有第一个字符不能是新行

我在用

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

但这种模式不允许出现新的线条


共 (1) 个答案

  1. # 1 楼答案

    我不是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也有类似的东西