【问题标题】:Java equivalent for Python's str.strip()Java 等效于 Python 的 str.strip()
【发布时间】:2012-03-06 12:11:26
【问题描述】:

假设我想删除字符串周围的所有"。在 Python 中,我会:

>>> s='"Don\'t need the quotes"'
>>> print s
"Don't need the quotes"
>>> print s.strip('"')
Don't need the quotes

如果我想删除多个字符,例如" 和括号:

>> s='"(Don\'t need quotes and parens)"'
>>> print s
"(Don't need quotes and parens)"
>>> print s.strip('"()')
Don't need quotes and parens

在 Java 中剥离字符串的优雅方法是什么?

【问题讨论】:

  • String 类有一个 replace() 方法。它应该满足您的需求。
  • See here 是详细讨论。

标签: java string


【解决方案1】:

假设我想删除字符串周围的所有"

与 Python 代码最接近的等价物是:

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

如果我想删除多个字符,例如" 和括号:

s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");

如果你可以使用Apache Commons Lang,那就是StringUtils.strip()

【讨论】:

  • +1 用于处理请求的多个字符。不过,它仍然会创建两个新字符串。
  • @AdamMatan:我认为 Common Lang 的 StringUtils.strip() 是首选方法。请参阅我的更新答案。
【解决方案2】:

Guava 库有一个方便的实用程序。该库包含CharMatcher.trimFrom(),它可以满足您的需求。您只需要创建一个与您要删除的字符匹配的CharMatcher

代码:

CharMatcher matcher = CharMatcher.is('"');
System.out.println(matcher.trimFrom(s));

CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));

在内部,这不会创建任何新的字符串,而只是调用s.subSequence()。由于它也不需要正则表达式,我猜它是最快的解决方案(当然也是最干净、最容易理解的)。

【讨论】:

    【解决方案3】:

    在java中,你可以这样做:

    s = s.replaceAll("\"",""),replaceAll("'","")
    

    此外,如果您只想替换“开始”和“结束”引号,您可以执行以下操作:

    s = s.replace("^'", "").replace("'$", "").replace("^\"", "").replace("\"$", "");
    

    或者如果简单地说:

    s = s.replaceAll("^\"|\"$", "").replaceAll("^'|'$", "");
    

    【讨论】:

    • 它已经相应地修改了我的答案..!!
    • 创建两个新字符串而不是一个不是浪费时间吗?
    • 请注意,字符串是“不可变的”,因此仅执行 ''' s.replace("\"","") ''' 是不够的。您必须重新分配变量的' 到结果字符串 's'。
    • 你“接受”的答案,有没有比我的好..??..我给了你 3 种不同的方式来解决..!!..至少,你可以投票我的回答..!!
    【解决方案4】:

    这将替换字符串开头和结尾的"()

    String str = "\"te\"st\"";
    str = str.replaceAll("^[\"\\(]+|[\"\\)]+$", "");
    

    【讨论】:

      【解决方案5】:

      试试这个:

      new String newS = s.replaceAll("\"", "");
      

      用无字符字符串替换双引号。

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2016-08-04
        • 2019-01-31
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        • 2010-10-30
        相关资源
        最近更新 更多