Reputation: 1020
I need to write regular expression that allows only digits, characters like & | . ( ) and spaces.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
List<String> input = new ArrayList<String>();
input.add("(0.4545 && 0.567) || 456"); // should PASS
input.add("9876-5-4321");
input.add("987-65-4321 (attack)");
input.add("(0.4545 && 0.567) || 456 && (me)");
input.add("0.456 && 0.567"); // should PASS
for (String ssn : input) {
boolean f = ssn.matches("^[\\d\\s()&|.]$");
if (f) {
System.out.println("Found good SSN: " + ssn);
}else {
System.out.println("Nope: " + ssn);
}
}
}
}
None above passed, why?
Upvotes: 2
Views: 5524
Reputation: 1026
Because your regular expression accepts single input only (either digits or characters or symbols you specified)
Use ^[\\d\\s()&|.]*$
for getting multiple times
'+ 1 or more'
? 0 or one
'* 0 or more'
Upvotes: 2
Reputation: 124215
You forgot to add +
after character class. Without it your regex will only accept one-character strings with characters from your character class. Try with
boolean f = ssn.matches("^[\\d\\s()&|.]+$");
Upvotes: 5