我有以下修复程序charset:
大写和小写:
A-Z,az
号码:
0-9
特殊字符:
Ñ,É,ñ,à,@,£,$,¥,è,é,ù,ì,ò,_,!,“,#,%,&,',(,),*,+,,, -,。,/,:,;,<,=,>,?,§,`,SPACE,CR,LF,€,[,],{,|,},^,〜,\,ß,Ä, Ö,Ü,ä,ö,ü
我尝试使用该库,Guava但我的String匹配为非ASCII唯一字符串:
if(!CharMatcher.ascii().matchesAllOf(myString)){
//String doesn't match
}
Run Code Online (Sandbox Code Playgroud)
我的输入字符串是:
smsBodyBlock.setBodyContent("A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Ä, Ö, Ü,a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, ä, ö, ü,0, 1, 2, 3, 4, 5, 6, 7, 8, 9,Ñ, É, ñ, à, @, £, $, ¥, è, é, ù, ì, ò, _, !, , #, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, §, `, SPACE, CR, LF, €, [, ], {, |, }, ^, ~, , ß\"");
Run Code Online (Sandbox Code Playgroud)
所以基本上是我上面写的整个字符集。它不符合ASCII
是否有任何快速,可靠的可伸缩方式来检查是否有除我预定义字符以外的其他字符?
这就是CharMatcher存在的原因,而您已经在使用它,只是没有充分利用它!
唯一的区别是您应该定义自己的字符集。
因此,我们开始:
CharMatcher letters = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'));
CharMatcher numbers = CharMatcher.inRange('0, '9');
CharMatcher specials = CharMatcher.anyOf("ÑÉñà@£$¥èéùìò_!\"#%&'()*+,-./:;<=>?§` \r\n€[]{|}^~\\ßÄÖÜäöü");
CharMatcher allMyCharacters = letters.or(numbers).or(specials);
// If you want performance, keep the line below. If not, remove it
allMyCharacters = allMyCharacters.precomputed();
if (allMyCharacters.matchesAllOf(myString)) {
//
}
Run Code Online (Sandbox Code Playgroud)
确保将allMyCharacters存储字段保存在某个地方,例如:
public class MyStringMatcher {
private static final CharMatcher myCharacters = createCharMatcher();
private static CharMatcher createCharMatcher() {
CharMatcher letters = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'));
CharMatcher numbers = CharMatcher.inRange('0, '9');
CharMatcher specials = CharMatcher.anyOf("ÑÉñà@£$¥èéùìò_!\"#%&'()*+,-./:;<=>?§` \r\n€[]{|}^~\\ßÄÖÜäöü");
return letters.or(numbers).or(specials).precomputed();
}
public static boolean matches(String string) {
return myCharacters.matchesAllOf(string);
}
}
Run Code Online (Sandbox Code Playgroud)