2014-10-30 113 views
-2

有沒有一種方法可以擺脫字符串前端和末尾的標記?在字符串前後擺脫標點的正則表達式

例如,

"hello," -> "hello" 
"hello;" -> "hello" 

換句話說,刪除所有標點後,之前,或者一個字內,除單引號和單短線,如果他們後面更多的字母。

更多的例子,

"lies,", "'This", "all-eating" and "deserv'd." 

將成爲

"lies", "this", "all-eating" and "deserv'd" 
+1

'後除去所有標點,之前,或word'內爲一個字內提供一個例子。並且不要忘記顯示你的嘗試。 – 2014-10-30 04:34:11

+0

「謊言」,「這個」,「所有食物」和「受保護的」,它們轉到「謊言」,「這個」,「所有食物」和「受保護的」 – paupau 2014-10-30 04:38:49

+0

什麼是預期產出?在你的問題中添加上面的評論。 – 2014-10-30 04:43:06

回答

0

使用poxix正則表達式項\p{Punct}

str = str.replaceAll("^\\p{Punct}*|\\p{Punct}+$|\\p{Punct}{2,}", "") 

中期字標點符號使用的是「兩個或兩個以上去除「 比賽。


一些測試代碼:

for (String str : new String[]{"hello,", "hello;", "li--es", "'This", "all-eating", "deserv'd."}) 
    System.out.println(str.replaceAll("^\\p{Punct}*|\\p{Punct}+$|\\p{Punct}{2,}", "")); 

輸出:

hello 
hello 
lies 
This 
all-eating 
deserv'd