[英]How do I check if a string contains at least one character from another string?
I'm using Java 6. I have a string that contains "special" characters -- "!@#$%^&*()_". 我正在使用Java6。我有一个包含“特殊”字符的字符串-“!@#$%^&*()_”。 How do I write a Java expression to check if another string, "password", contains at least one of the characters defined in the first string?
如何编写Java表达式以检查另一个字符串“ password”是否至少包含第一个字符串中定义的字符之一? I have
我有
regForm.getPassword().matches(".*[\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+].*")
but I don't want to hard-code the special characters, rather load them into a string from a properties file. 但是我不想对特殊字符进行硬编码,而是将它们从属性文件加载到字符串中。 So I'm having trouble figuring out how to escape everything properly after I load it from the file.
因此,在从文件中加载所有内容后,我很难弄清楚如何正确地转义所有内容。
You can try creating regex from string that contains special characters and escape symbols using Pattern.quote . 您可以尝试使用Pattern.quote从包含特殊字符和转义符号的字符串中创建正则表达式。 Try this:
尝试这个:
String special = "!@#$%^&*()_";
String pattern = ".*[" + Pattern.quote(special) + "].*";
regFrom.getPassword().matches(pattern);
I think simple looping the regex to check each character might work better and will work for all the cases : 我认为简单循环正则表达式以检查每个字符可能会更好,并且在所有情况下都适用 :
String special = "!@#$%^&*()_";
boolean found = false;
for (int i=0; i<special.length(); i++) {
if (regFrom.getPassword().indexOf(special.charAt(i)) > 0) {
found = true;
break;
}
}
if (found) { // password has one of the allowed characters
//...
//...
}
One option is to use StringTokenizer
, and see if it returns more than 1 substring. 一种选择是使用
StringTokenizer
,看看它是否返回多个子字符串。 It has a constructor that allows specifying the characters to split by. 它有一个构造函数,允许指定要分割的字符。
Anyway, my favourite option would be just iterating the characters and using String.indexOf
. 无论如何,我最喜欢的选项是迭代字符并使用
String.indexOf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.