簡體   English   中英

替換匹配的正則表達式的 substring

[英]replace substring of matched regex

我獲取了一些 html 並進行了一些字符串操作並得到了一個字符串

string sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n"

我想找到所有成分行並刪除空格和換行符

2分升。 面粉4杯糖

到目前為止,我的方法如下。

Pattern p = Pattern.compile("[\\d]+[\\s\\w\\.]+");
Matcher m = p.matcher(Result);

while(m.find()) {
  // This is where i need help to remove those pesky whitespaces
}

sample = sample.replaceAll("[\\n ]+", " ").trim();

Output:

2 dl. flour 4 cups of sugar

開頭沒有空格,結尾也沒有空格。

它首先用一個空格替換所有空格和換行符,然后從 begging / end 修剪多余的空格。

以下代碼應該適合您:

String sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";
Pattern p = Pattern.compile("(\\s+)");
Matcher m = p.matcher(sample);
sb = new StringBuffer();
while(m.find())
    m.appendReplacement(sb, " ");
m.appendTail(sb);
System.out.println("Final: [" + sb.toString().trim() + ']');

OUTPUT

Final: [2 dl. flour 4 cups of sugar]

我認為這樣的事情對你有用:

String test = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";

/* convert all sequences of whitespace into a single space, and trim the ends */
test = test.replaceAll("\\s+", " ");

我假設\n不是實際的換行符,但它也適用於linefeeds 這應該可以正常工作:

test=test.replaceAll ("(?:\\s|\\\n)+"," ");

如果沒有textual \n它可以更簡單:

test=test.replaceAll ("\\s+"," ");

您需要修剪前導/尾隨空格。

我使用 RegexBuddy 工具檢查任何單個正則表達式,在這么多語言中非常方便。

您應該能夠使用標准String.replaceAll(String, String) 第一個參數將采用您的模式,第二個參數將采用空字符串。

s/^\s+//s
s/\s+$//s
s/(\s+)/ /s

運行這三個替換(用空替換前導空格,用空替換尾隨空格,用空格替換多個空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM