Python 的 str.strip() 的 Java 等价物

标签 java string

假设我想删除字符串周围的所有 "。在 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 中去除字符串的优雅方法是什么?

最佳答案

Suppose I would like to remove all " surrounding a string

最接近 Python 代码的是:

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

And if I want to remove multiple characters, e.g. " and parentheses:

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

如果可以使用Apache Commons Lang , 有 StringUtils.strip() .

关于Python 的 str.strip() 的 Java 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9583467/

相关文章:

Java 未捕获的全局异常处理程序

regex - Python : Count items, 将计数存储为变量,用于将字符串替换为外部文件中的项目数的语句

string - 如何在不复制的情况下将两个字符串连接成第三个字符串?

javascript - String.prototype.myFunction 不返回字符串?

c++ - 为什么这些字符串不会在 C++ 中连接?

java - 在 CalendarView 中为日期着色

java - 任何自动化 Eclipse 工作区设置的方法?

Java 反射 - 调用具有私有(private)构造函数的泛型类的静态方法

java - 平铺 map 加载问题

string - "loop rolling algorithm"的解释