【问题标题】:Only removing X spaces in a Java String仅删除 Java 字符串中的 X 空格
【发布时间】:2013-12-09 04:16:48
【问题描述】:

所以我正在为“Item #”解析以下形式的文件(A 和 B 不包括在格式中),将它们添加到列表中,为清楚起见,.'s 是空格:

Someword: a list of words of any length      (A)
....Item 1                                   (B)
....Item 2
.Item 3

其中 (A) 部分始终采用这种形式,而 B 部分始终使用制表符(4 个空格)或单个空格缩进。我的结果是 {Item 1,Item 2,Item 3}。到目前为止,我刚刚使用了一个正则表达式来匹配 (A) 部分,然后添加了以下行并调用了 .trim() 。

我的问题是,我将如何解析看起来像这样的东西:

Someword: a list of words of any length 
........Item 1

这样第二行就有 8 个空格。所以我想忽略前 4 个(或可能是 1 个)空格,并捕获其他所有内容,如果 x 在这种情况下是空格,则会导致 {....Item 1}。

【问题讨论】:

  • 如果您要求使用正则表达式,( |\t)(.*) 将匹配前面有 4 个空格或制表符的项目,并且项目(可能包括空格)将在第二个 sumbatch 中。但是为什么还要保留格式呢?
  • 你提供的例子不清楚。添加 真实 示例(一个“有效”,一个无效),显示您的 当前 代码,以及输入“无效”的请求输出是什么工作”。

标签: java regex


【解决方案1】:

您可以使用一个正则表达式,一次通过即可获取所有项目:

代码

String str = "Someword: a list of words of any length\r\n" +
             "    Item 1\r\n" + // 4 spaces at the beginning
             "    Item 2\r\n" + // 4 spaces at the beginning
             " Item 3\r\n" + // 1 space at the beginning
             "        Item 4\r\n"; // 8 spaces at the beginning

Pattern p = Pattern.compile("(?m)^\\s+(Item\\s+\\d+)$");

Matcher m = p.matcher(str);
while(m.find()) {
    System.out.println(m.group(1));
}

输出

Item 1
Item 2
Item 3
Item 4

说明

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多