2012-03-06 98 views
11

假設我想刪除圍繞字符串的所有"。在Python中,我會:用於Python的str.strip()的Java等價物

>>> s='"Don\'t need the quotes"' 
>>> print s 
"Don't need the quotes" 
>>> print s.strip('"') 
Don't need the quotes 

如果我想刪除多個字符,例如"和括號:

>> s='"(Don\'t need quotes and parens)"' 
>>> print s 
"(Don't need quotes and parens)" 
>>> print s.strip('"()') 
Don't need quotes and parens 

什麼是剝離Java中的字符串優雅的方式?

+0

String類有一個replace()方法。它應該適合你的需求。 – wuppi 2012-03-06 12:14:27

+0

[看這裏](http://stackoverflow.com/a/2088900/593709)是一個詳細的討論。 – 2012-03-06 12:20:20

回答

9

假設我想刪除所有"圍繞一個字符串

最接近相當於Python代碼是:

s = s.replaceAll("^\"+", "").replaceAll("\"+$", ""); 

如果我要刪除多個字符,例如"和括號:

s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", ""); 

如果你可以使用Apache Commons Lang,有StringUtils.strip()

+0

+1爲了處理多個字符的請求,它仍然會創建兩個新的字符串, – 2012-03-06 12:28:51

+1

@AdamMatan:我認爲Common Lang的'StringUtils.strip()'是首選的方法。 – NPE 2012-03-06 12:30:18

0

這取代"()在開始和結束字符串

String str = "\"te\"st\""; 
str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", ""); 
1

在Java中,你可以做到這一點,如:

s = s.replaceAll("\"",""),replaceAll("'","") 

此外,如果你只是想取代「開始」和「結束」引號,您可以執行如下操作:

s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", ""); 

或者,如果簡單地說:

s = s.replaceAll("^\"|\"$", "").replaceAll("^'|'$", ""); 
+0

它相應地修改了我的答案.. !! – 2012-03-06 12:23:19

+0

不是浪費時間,創建兩個新的字符串而不是一個? – 2012-03-06 12:24:04

+0

請注意,字符串是「不可變的」,因此僅僅執行'''s.replace(「\」「,」「)'''是不夠的,您必須將變量's'重新賦值給結果字符串'。 – 2012-03-06 12:33:54

0

試試這個:

new String newS = s.replaceAll("\"", ""); 

有沒有個字符的字符串替換雙引號。

6

Guava庫有一個方便的工具。該庫包含CharMatcher.trimFrom(),它可以做你想做的。您只需創建一個CharMatcher,它與要刪除的字符匹配。

代碼:

CharMatcher matcher = CharMatcher.is('"'); 
System.out.println(matcher.trimFrom(s)); 

CharMatcher matcher2 = CharMatcher.anyOf("\"()"); 
System.out.println(matcher2.trimFrom(s)); 

內部,這不會產生任何新的字符串,而只是調用s.subSequence()。因爲它也不需要Regexps,所以我猜它是最快的解決方案(並且肯定是最清晰和最容易理解的)。