-->

卸下串不在白名单中的所有字符(Remove all characters from string w

2019-07-21 02:30发布

我想编写Java代码这将删除所有不想要的字符,让那只是白名单中的人。

例:

String[] whitelist = {"a", "b", "c"..."z", "0"..."9", "[", "]",...}

我想有只字母(下限和大写)和数字+一些未来字符我想补充。 然后我就开始for()循环的字符串中的每个字符,并与空字符串代替它,如果它不在白名单中。

但是,这不是很好的解决方案。 也许这可以在某种程度上使用模式(正则表达式)来完成? 谢谢。

Answer 1:

是的,你可以使用String.replaceAll这需要一个正则表达式:

String input = "BAD good {} []";
String output = input.replaceAll("[^a-z0-9\\[\\]]", "");
System.out.println(output); // good[]

或番石榴你可以使用一个CharMatcher

CharMatcher matcher = CharMatcher.inRange('a', 'z')
                          .or(CharMatcher.inRange('0', '9'))
                          .or(CharMatcher.anyOf("[]"));
String input = "BAD good {} []";
String output = matcher.retainFrom(input);

这恰恰说明小写版本,使其更容易证明。 要包含大写字母,使用"[^A-Za-z0-9\\[\\]]"在正则表达式(和你想要的任何其他符号) -和为CharMatcher你可以or将其与CharMatcher.inRange('A', 'Z')



Answer 2:

你可以尝试搭配一切,这是不是在你的白名单中,并用一个空字符串替换它:

String in = "asng $%& 123";
//this assumes your whitelist contains word characters and whitespaces, adapt as needed
System.out.println(in.replaceAll( "[^\\w\\s]+", "" )); 


文章来源: Remove all characters from string which are not on whitelist