Java 删除第一个和最后一个双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21873191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing First and Last Double Quotes
提问by Lemon Juice
I have set of String
s where the first and last characters are double quotes. Below is an example.
我有一组String
s ,其中第一个和最后一个字符是双引号。下面是一个例子。
String x = "‘Gravity' tops the box office for 3rd week | New York Post"
Some other strings will contain double quotes in the middle of the text, so I can't use String.replaceAll()
. I just need to remove the first and last double quotes. How can I do this?
其他一些字符串将在文本中间包含双引号,所以我不能使用String.replaceAll()
. 我只需要删除第一个和最后一个双引号。我怎样才能做到这一点?
采纳答案by Hari Menon
If the "
characters are always going to be the first and last ones, you don't need a regex. Just use substring
:
如果"
字符总是第一个和最后一个,则不需要正则表达式。只需使用substring
:
x = x.substring(1, x.length() - 1)
回答by Evgeniy Dorofeev
try this regex
试试这个正则表达式
s = s.replaceAll("\"(.+)\"", "");
回答by Evgeniy Dorofeev
Try this code:
试试这个代码:
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);
}
}
it gives:
它给:
‘Gravity' tops the box office for 3rd week | New York Post
回答by RkHirpara
The best thing you can do is
你能做的最好的事情就是
str.Trim('"')
str.Trim('"')
Double quote is enclosed in two single quotes, and thats it. This technique is not limited to just double quotes but you can do for any character.
双引号括在两个单引号中,仅此而已。这种技术不仅限于双引号,而且您可以对任何字符执行此操作。
Furthermore, if you wants to do the same thing only for either start or end character (not both) even then there is an option. You can do the same thing like
此外,如果您只想为开始或结束字符(不是两者)做同样的事情,即使有一个选项。你可以做同样的事情
str.TrimEnd('"')
this removes only the last character and
这仅删除最后一个字符和
str.TrimStart('"')
str.TrimStart('"')
removes only the only first(Start) character
仅删除唯一的第一个(开始)字符
回答by Asad
Try org.apache.commons.lang3.StringUtils#strip(String str,String stripChars)
试试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!
All give:
都给:
‘Gravity' tops the box office for 3rd week | New York Post