2014-02-19 64 views
3

我有一组String s,其中第一个和最后一个字符是双引号。下面是一个例子。删除第一个和最后一个双引号

String x = "‘Gravity’ tops the box office for 3rd week | New York Post" 

一些其他字符串将包含文本的中间双引号,所以我不能使用String.replaceAll()。我只需要删除第一个和最后一个双引号。我怎样才能做到这一点?

+3

如果您知道关于'^'和'$'的信息,您可以使用'replaceAll()'。去查找Javadoc的'Pattern'类。 –

+0

随着交替(''''''')。 –

+0

是的,这也有帮助! –

回答

8

如果"字符总是第一个也是最后一个,那么不需要正则表达式。只需使用substring

x = x.substring(1, x.length() - 1) 
+0

+1来获取问题描述中重要信息的解决方案。 –

+0

伟大的解决方案! –

+0

,但没有与我一起工作'console.log(someStr.replace(/ [''] +/g,''));'因为我有传情和其他东西,这很准确 – shareef

3

尝试这个表达式

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

试试这个代码:

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 
+1

我不是一个Java人说,但不会''System.out.println(x)'也给出相同的输出。因为字符串中没有''要替换?或者我错过了关于Java字符串的神奇东西? –

+0

是的,你说得对。 –

-1

你能做的最好的事情是

str.Trim('"')

双引号括在两个单引号中,就是这样。 这种技术不仅限于双引号,而且可以用于任何角色。另外,如果你只想为开始或结束字符(不是两个)做同样的事情,那么即使有,也有一个选项。你可以做同样的事情,就像

str.TrimEnd('"') 

这仅删除最后一个字符 和

str.TrimStart('"')

只删除仅第一(开始)字符

+0

那不是标准的java,是吗? – Preuk

0

尝试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 
相关问题