Removing the first and last double quotes

I have a set Stringwhere the first and last characters are double quotes. The following is an example.

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

Some other lines will contain double quotes in the middle of the text, so I cannot use String.replaceAll(). I just need to remove the first and last double quotes. How can i do this?

+3
source share
5 answers

If the characters are "always the first and last, you do not need a regular expression. Just use substring:

x = x.substring(1, x.length() - 1)
+8
source

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);     
    }
}   

He gives:

‘Gravity’ tops the box office for 3rd week  | New York Post
+4
source

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

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
0

, ,

str.Trim('"')

The double quote is enclosed in two single quotes, and that is it. This method is not limited to double quotes, but you can do for any character.

In addition, if you want to do the same only for the beginning or end of a character (not for both), even then there is an option. You can do the same as

str.TrimEnd('"')

this only removes the last character and

str.TrimStart('"')

deletes only the first (start) character

-1
source

All Articles