我有一組String
s,其中第一個和最後一個字符是雙引號。下面是一個例子。刪除第一個和最後一個雙引號
String x = "‘Gravity’ tops the box office for 3rd week | New York Post"
一些其他字符串將包含文本的中間雙引號,所以我不能使用String.replaceAll()
。我只需要刪除第一個和最後一個雙引號。我怎樣才能做到這一點?
我有一組String
s,其中第一個和最後一個字符是雙引號。下面是一個例子。刪除第一個和最後一個雙引號
String x = "‘Gravity’ tops the box office for 3rd week | New York Post"
一些其他字符串將包含文本的中間雙引號,所以我不能使用String.replaceAll()
。我只需要刪除第一個和最後一個雙引號。我怎樣才能做到這一點?
如果"
字符總是第一個也是最後一個,那麼不需要正則表達式。只需使用substring
:
x = x.substring(1, x.length() - 1)
+1來獲取問題描述中重要信息的解決方案。 –
偉大的解決方案! –
,但沒有與我一起工作'console.log(someStr.replace(/ [''] +/g,''));'因爲我有傳情和其他東西,這很準確 – shareef
嘗試這個表達式
s = s.replaceAll("\"(.+)\"", "$1");
試試這個代碼:
public class Example {
public static void main(String[] args) {
String x = "\"‘Gravity’ tops the box office for 3rd week | New York Post\"";
String string = x.replaceAll("^\"|\"$", "");
System.out.println(string);
}
}
它給:
‘Gravity’ tops the box office for 3rd week | New York Post
我不是一個Java人說,但不會''System.out.println(x)'也給出相同的輸出。因爲字符串中沒有''要替換?或者我錯過了關於Java字符串的神奇東西? –
是的,你說得對。 –
你能做的最好的事情是
str.Trim('"')
雙引號括在兩個單引號中,就是這樣。 這種技術不僅限於雙引號,而且可以用於任何角色。另外,如果你只想爲開始或結束字符(不是兩個)做同樣的事情,那麼即使有,也有一個選項。你可以做同樣的事情,就像
str.TrimEnd('"')
這僅刪除最後一個字符 和
str.TrimStart('"')
只刪除僅第一(開始)字符
那不是標準的java,是嗎? – Preuk
嘗試org.apache.commons.lang3.StringUtils#strip(String str,String stripChars)
StringUtils.strip("‘Gravity’ tops the box office for 3rd week | New York Post", "\""); // no quotes
StringUtils.strip("\"‘Gravity’ tops the box office for 3rd week | New York Post\"", "\""); // with quotes
StringUtils.strip("\"\"\"‘Gravity’ tops the box office for 3rd week | New York Post\"", "\"\""); // with multiple quotes - beware all of them are trimmed!
所有給出:
‘Gravity’ tops the box office for 3rd week | New York Post
如果您知道關於'^'和'$'的信息,您可以使用'replaceAll()'。去查找Javadoc的'Pattern'類。 –
隨着交替(''''''')。 –
是的,這也有幫助! –