有 Java 编程相关的问题?

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

java按空格或按空格拆分字符串\n

我想将字符串拆分为两行:空格(“”)或新行(\n)

我所尝试的:

message.split("\\r?\\n? ");

它不按空间分割,但不按\n旋转:

The way I see it we got two options. Option one, we take the easy way
out. It's quick and painless. I'm not a fan of option one. Option two,
We fight.

进入:

[The, way, I, see, it, we, got, two, options., Option, one,, we, take, the, easy, way, out., It's, quick, and, painless., I'm, not, a, fan, of, option, one.Option, two,, We, fight.]

注意one.Option是数组中的一个单元格


共 (2) 个答案

  1. # 1 楼答案

    "\\r?\\n? "
    

    这告诉它通过"\\r\\n ""\\n ""\\r "" "进行拆分,但决不能通过"\\r""\\n""\\r\\n"进行拆分,而不使用空格

    下面将告诉它通过至少一个字符的"\\r""\\n"" "的任何连续组合进行拆分:

    "[\\r\\n ]+"
    
  2. # 2 楼答案

    从注释中,尝试"\\s+"拆分一个或多个空白字符。这包括空格、制表符、换行符、回车符、换行符等,所以对于您想要的内容来说,它可能有点太大了

    final String message = "The way I see it we got two options. Option one, we take the easy way\n" +
            "out. It's quick and painless. I'm not a fan of option one. Option two,\n" +
            "We fight.";
    System.out.println(String.join(", ", message.split("\\s+")));
    

    产生

    The, way, I, see, it, we, got, two, options., Option, one,, we, take, the, easy, way, out., It's, quick, and, painless., I'm, not, a, fan, of, option, one., Option, two,, We, fight.