2012-03-21 57 views
0

我想保留句子的前兩個單詞和最後一個單詞,包括句末的問號。保留前兩個單詞和句子的最後一個單詞

wie ging er ook alweer allemaal mee wat drink in Utrecht?

應該變成

當句子是3個字也應該工作。 所以

wie ging烏得勒支?

應保持不變

無論我怎麼努力,我找了幾個字母或什麼,可能有人伸出援助之手? 我有一本關於正則表達式的好書,但我沒有時間,直到夏天:(

+1

爲什麼不告訴我們你嘗試過什麼? :) – 2012-03-21 12:16:22

+1

定義「單詞」和「句子」。 – 2012-03-21 12:17:15

+1

再次,這是**不是**正則表達式適合的東西,常規的字符串操作方法會得到更好的結果。 – 2012-03-21 12:17:38

回答

2

這是不使用正則表達式的適當位置。

在Java中執行此操作的正確方法是使用BreakIterator來檢測「Words」並根據您的邏輯處理它們。僅僅分割一個字符在所有語言中可能在語義上都不是正確的。

打印第一個元素:

public static void printFirst(BreakIterator boundary, String source) { 
    int start = boundary.first(); 
    int end = boundary.next(); 
    System.out.println(source.substring(start,end)); 
} 

打印最後一個元素:

public static void printAt(BreakIterator boundary, int pos, String source) { 
    int end = boundary.following(pos); 
    int start = boundary.previous(); 
    System.out.println(source.substring(start,end)); 
} 
+0

酷真的親。 我必須記住這爲未來的項目:) 我建立一個textAnalyser一次,這應該是它的好。 是啊是否BreakIterator使用正則表達式,如果不是什麼使它如此好? – clankill3r 2012-03-28 20:45:54

+0

我會說,看它的工作原理,但它更注意區域設置和unicode而不是「啞」正則表達式。 – 2012-03-29 12:24:56

0

只是在空格分裂,並採取前兩個/最後一個,根據需要從前兩個字剝離標點符號,並確保長度,在使用正則表達式沒有點。

4

嘗試......使用String.split()

String s = "wie ging er ook alweer allemaal mee wat drinken in Utrecht?"; 
String words[] = s.split(" "); 
String firstTwo = words[0] + " " + words[1]; // first two words 
String lastOne = words[words.length - 1]; // last one 
+0

酷感謝的人。 – clankill3r 2012-03-28 20:44:46

1

正則表達式溶液

^((?:\w+\s+){2}).*?(\S+)$ 

public static void printLast(BreakIterator boundary, String source) { 
    int end = boundary.last(); 
    int start = boundary.previous(); 
    System.out.println(source.substring(start,end)); 
} 

打印在規定位置上的元素

$1$2

更換看到它here on Regexr

相關問題