1

我有一个这样的字符串:

Mr Moh Jo\n
Address\n
 33333 City\n\n
Aland Islands

我想删除每行开头的空格并用以下代码结束每行的结尾,但它不起作用

    public static String trimWhiteSpaceFromTheBeginingAndEndOFTheLine(
        String string) {
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(string);
    StringBuffer out = new StringBuffer();
    while (m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);

    return out.toString();
}

预期结果:

Mr Moh Jo\n
Address\n
33333 City\n\n
Aland Islands
4

5 回答 5

5

只需在正则表达式中启用多行标志。

Pattern.compile("(?m)^[\\s&&[^\\n]]+|[\\s+&&[^\\n]]+$");

巴姆。完毕。

您还可以用调用替换所有匹配器代码replaceAll

public static String trimWhiteSpaceFromTheBeginingAndEndOFTheLine(
    String string) {
    return string.replaceAll("(?m)^[\\s&&[^\\n]]+|[\\s+&&[^\\n]]+$", "");
}
于 2013-10-09T10:22:51.947 回答
2

为什么不使用,它正是你想要的

 String.trim()

你可以做这样的事情:

String address = 
"Mr Moh Jo \n" + 
"Address \n" +
" 33333 City \n" +
"Aland Islands \n";

String [] addrLines = address.split("\n");
StringBuffer formatedAddress = new StringBuffer();

for(String line : addrLines)
{
    formatedAddress.append(line.trim()+ "\n");
}

System.out.println("formatedAddress: ");
System.out.println(formatedAddress.toString());
于 2013-10-09T10:11:53.710 回答
0

您的输入是单个字符串。所以trim()只省略 initial 和 end whitespaces,而不是中间。所以将字符串拆分为lineBreak. 以及trim()所有单独的值。

       String[] inputArray = sample.split("\n");
       StringBuilder stringBuilder = new StringBuilder();
       for(String value : inputArray)
       {
           stringBuilder.append(value.trim());
           stringBuilder.append("\n");
       }
        System.out.println("Sample : "+stringBuilder.toString());
于 2013-10-09T10:22:19.473 回答
0

尝试这个 :

 String s = "Your multi line string";
      System.out.println(s);

      String[] splitString = s.split("\n");
      s="";

      for(int i =0;i<splitString.length;i++)
      {
          splitString[i]  = splitString[i].trim();
          s+=splitString[i]+"\n";

      }
      System.out.println(s);
于 2013-10-09T10:11:47.403 回答
0

像这样的东西?

private void doTrim(String str) throws Exception {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new StringReader(str));
    String line;
    String NL = System.getProperty("line.separator");
    while( (line=reader.readLine())!=null ) {
        sb.append(line.trim());
        sb.append(NL);
    }
    System.out.println(">>" + str + "<<");
    str = sb.toString().trim();
    System.out.println(">>" + str + "<<");
}

或硬核版本循环字符串字符并更新新缓冲区。这会将尾随窗口 "\r\n" 修剪为 unix "\n" 换行符。可以避免小的 idxTail 优化 newBuf 并且只使用 buf[]。

private String trimLeadingAndTrailingSpaces(String str) {
    char[] buf = str.toCharArray();
    char[] newBuf = new char[buf.length];
    int newCount=0;
    boolean isBegin=true;
    int trailingSpaces=0;
    for(int idx=0; idx<buf.length; idx++) {
        char ch = buf[idx];
        if (isBegin) {
            if (ch!=' ') {
                isBegin=false;
                newBuf[newCount]=ch;
                newCount++;
            }
        } else {
            if (ch==' ' || ch=='\r') {
                trailingSpaces++;
            } else if (ch=='\n') {
                if (trailingSpaces>0) newCount -= trailingSpaces;
                trailingSpaces=0;
                isBegin=true;
            } else if (trailingSpaces>0) {
                trailingSpaces=0;
            }
            newBuf[newCount]=ch;
            newCount++;
        }
    }
    return new String(newBuf, 0, newCount-trailingSpaces);
}
于 2013-10-09T10:24:54.873 回答