Java regex - expression with exactly one whitespace

后端 未结 6 1886
攒了一身酷
攒了一身酷 2021-01-14 12:08

I want to match all expressions with exactly one whitespace. Currently, I\'m using [^\\\\s]*\\\\s[^\\\\s]*. That doesn\'t seem like a very good way, though.

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 12:53

    String[] ss = { " ", "abc", "a bc", "a b c d" };
    Matcher m = Pattern.compile("^\\S*\\s\\S*$").matcher("");
    for (String s : ss)
    {
      if (m.reset(s).matches())
      {
        System.out.printf("%n>>%s<< OK%n", s);
      }
    }
    

    output:

    >> << OK
    
    >>a bc<< OK
    

提交回复
热议问题