Dave
Dave

Reputation: 19110

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 -- "!@#$%^&*()_". 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

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.

Upvotes: 0

Views: 18744

Answers (3)

anubhava
anubhava

Reputation: 784998

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

Upvotes: 2

SJuan76
SJuan76

Reputation: 24780

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.

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

Upvotes: 0

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

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

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

Upvotes: 11

Related Questions