【问题标题】:Removing First and Last Double Quotes删除第一个和最后一个双引号
【发布时间】:2014-02-19 06:52:49
【问题描述】:

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

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

其他一些字符串会在文本中间包含双引号,所以我不能使用String.replaceAll()。我只需要删除第一个和最后一个双引号。我该怎么做?

【问题讨论】:

  • 如果您了解^$,您可以使用replaceAll()。去查找Pattern 类的Javadoc。
  • 连同交替 (|)。
  • 是的,这也有帮助!
  • 或者只是不使用正则表达式,只需使用 String API 来获取您的子字符串。
  • 我是唯一一个没有在该字符串中看到前导和尾随双引号的人吗?

标签: java regex string


【解决方案1】:

如果" 字符始终是第一个和最后一个字符,则不需要正则表达式。只需使用substring:

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

【讨论】:

  • +1 表示可以捕获问题描述中的重要信息的解决方案。
  • 但没有和我一起工作 console.log(someStr.replace(/['"]+/g, '')); 因为我有预告片和其他东西,这非常准确
【解决方案2】:

试试这个正则表达式

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

【讨论】:

    【解决方案3】:

    试试这个代码:

    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) 不会也给出相同的输出。由于字符串中没有 "'s 来替换?或者我错过了一些关于 Java 字符串文字的神奇之处?
    【解决方案4】:

    试试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
    

    【讨论】:

      【解决方案5】:

      如果字符串不是一直有那个引号,并且你不确定它是否会被引用,你可以使用下面的正则表达式;

      str.replace(/^\"(.+)\"$/,"$1")
      

      这在从样式表中获取font-family 时也很有用。字体族属性可能返回 Arial"Open Sans" 之类的值。

      【讨论】:

        【解决方案6】:

        你能做的最好的事情就是

        str.Trim('"')

        双引号括在两个单引号中,仅此而已。 这种技术不仅限于双引号,还可以用于任何字符。

        此外,如果您只想对开始或结束字符(而不是两者)执行相同的操作,那么即使有一个选项。你可以做同样的事情,比如

        str.TrimEnd('"')
        

        这只会删除最后一个字符 和

        str.TrimStart('"')

        只删除唯一的第一个(开始)字符

        【讨论】:

        • 那不是标准的java,是吗?
        猜你喜欢
        • 2014-11-23
        • 1970-01-01
        • 2014-09-16
        • 2011-03-06
        • 2012-04-01
        • 1970-01-01
        • 2023-02-16
        • 2014-07-13
        相关资源
        最近更新 更多