輸入字符串:Java的正則表達式樂趣 - 有句玩
Lorem存有尖。 Lorem ipsum loprem ipsum septum #match this#, lorem ipsum #match this too#。 #與此不符,因爲它在#期後已經是 。
希望的輸出:
Lorem存有尖端。 #match this##match this too# Lorem ipsum loprem ipsum septum,lorem ipsum。 #與此不符,因爲它在#期後已經是 。
注意#match此#和#match這太#都已經被旁邊最近一段時間移動()。基本上,所有的東西都是##應該移動到左邊最近的時間段。
RegEx和Java String處理能完成這個嗎?
這最基本的正則表達式匹配#什麼#是這樣的:
\#(.*?)\#
我有超出的困難。
編輯:您不必告訴我如何編寫完整的程序。我只需要一個足夠的正則表達式解決方案,然後我會嘗試自己的字符串操作。
這裏是我的解決方案從glowcoder的回答得出:
public static String computeForSlashline(String input) {
String[] sentences = input.split("\\.");
StringBuilder paragraph = new StringBuilder();
StringBuilder blocks = new StringBuilder();
Matcher m;
try {
// Loop through sentences, split by periods.
for (int i = 0; i < sentences.length; i++) {
// Find all the #____# blocks in this sentence
m = Pattern.compile("(\\#(.*?)\\#)").matcher(sentences[i]);
// Store all the #____# blocks in a single StringBuilder
while (m.find()) {
blocks.append(m.group(0));
}
// Place all the #____# blocks at the beginning of the sentence.
// Strip the old (redundant) #____# blocks from the sentence.
paragraph.append(blocks.toString() + " " + m.replaceAll("").trim() + ". ");
// Clear the #____# collection to make room for the next sentence.
blocks.setLength(0);
}
} catch(Exception e) { System.out.println(e); return null; }
// Make the paragraph look neat by adding line breaks after
// periods, question marks and #_____#.
m = Pattern.compile("(\\. |\\. |\\?|\\])").matcher(paragraph.toString());
return m.replaceAll("$1<br /><br />");
}
這給了我所需的輸出。但有一個問題:如果在#__#之間存在一段時間(例如:#史密斯女士在敏感點#中踢史密斯女士),input.split("\\.");
一行將打破#__#。所以我會用RegEx替換input.split()
行。
蕩,那些史密斯肯定不會相處的,不是嗎? – corsiKa