gpt4 book ai didi

regex - 使用正则表达式从字符串中删除垃圾字符

转载 作者:行者123 更新时间:2023-12-04 14:22:22 26 4
gpt4 key购买 nike

我想从 a-z 和 A-Z 以外的字符串中删除字符。为其创建了以下功能,并且工作正常。

public String stripGarbage(String s) {
String good = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
String result = "";
for (int i = 0; i < s.length(); i++) {
if (good.indexOf(s.charAt(i)) >= 0) {
result += s.charAt(i);
}
}
return result;
}

谁能告诉我实现相同目标的更好方法。可能正则表达式可能是更好的选择。

问候

哈利

最佳答案

干得好:

result = result.replaceAll("[^a-zA-Z0-9]", "");

但是如果你理解你的代码并且它是可读的,那么也许你有最好的解决方案:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

关于regex - 使用正则表达式从字符串中删除垃圾字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2943264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com