java 如何检查一个字符串是否至少包含另一个字符串中的一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16694251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:40:55  来源:igfitidea点击:

How do I check if a string contains at least one character from another string?

javaregex

提问by Dave

I'm using Java 6. I have a string that contains "special" characters -- "!@#$%^&*()_". 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? I have

我使用的是 Java 6。我有一个包含“特殊”字符的字符串——“!@#$%^&*()_”。如何编写 Java 表达式来检查另一个字符串“密码”是否至少包含第一个字符串中定义的一个字符?我有

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.

但我不想对特殊字符进行硬编码,而是将它们从属性文件加载到字符串中。所以我在从文件中加载它后无法弄清楚如何正确地转义所有内容。

回答by Mikita Belahlazau

You can try creating regex from string that contains special characters and escape symbols using Pattern.quote. Try this:

您可以尝试使用Pattern.quote从包含特殊字符和转义符号的字符串创建正则表达式。试试这个:

String special = "!@#$%^&*()_";
String pattern = ".*[" + Pattern.quote(special) + "].*";
regFrom.getPassword().matches(pattern);

回答by anubhava

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
   //...
   //...
}

回答by SJuan76

One option is to use StringTokenizer, and see if it returns more than 1 substring. It has a constructor that allows specifying the characters to split by.

一种选择是使用StringTokenizer, 并查看它是否返回超过 1 个子字符串。它有一个构造函数,允许指定要拆分的字符。

Anyway, my favourite option would be just iterating the characters and using String.indexOf.

无论如何,我最喜欢的选择就是迭代字符并使用String.indexOf.