我正在尝试筛选字符串,使其仅包含我允许的字符。例如,假设我允许字母[a-z](不区分大小写)和下划线('''')。
假设我有字符串: "I am a happy_bear and I sk@8 because it's gr8"
我希望它被过滤为: "I am a happy_bear and I sk because its gr"
到目前为止,我尝试了:
//Define a method to check allowed charachters
private boolean checkAllowed(Character ch) {
return Character.isLetter(ch) || ch == '_';
}
// loop through string
for (int i = 0; i < someString.length(); i++) {
if (this.checkAllowed(someString.charAt(i)) {
// append to a list
}
}
如何筛选字符串以仅包含允许的字符?这是否可以通过流式过滤实现?如果没有regex,这能做得更容易吗(我正在寻找更好的方法)
2条答案
按热度按时间pwuypxnk1#
如果您愿意使用第三方库,那么以下内容将适用于eclipse集合。
注意:我是eclipse集合的提交者。
z6psavjg2#
这是否可以通过流式过滤实现?
是的: