I am trying to figure out how to take a comma-separated string as input and detect if there are any strings inside it that do not match the following set
{FF,SF,FB,SB,Pause}
So as I parse the string (which can be any combination of the above) if it detects “FfdsG” for example it should throw an error. I assume that I can use some sort of regex to accomplish this or a series of ifs.
EDIT….
Is my implementation bad? I am converting the string to all lower and then comparing. No matter what I send in as input (FB or FB,FF or whatever) it seems its flagging everything is bad…
`public static String check(String modes) {
String s = modes;
String lower = s.toLowerCase();
HashSet<String> legalVals = new HashSet<String>();
legalVals.add("ff");
legalVals.add("sf");
legalVals.add("fb");
legalVals.add("sb");
legalVals.add("pause");
String valToCheck = lower;
if (legalVals.contains(valToCheck)) { //False
String str = modes;
} else {
return "Bad value: " + modes;
}
return modes;
}
To be clear, the input string can be any combination of the 5 valid values i listed. it could be 1 of them or all 5. I am just trying to detect if at any time a value is detected that is not on of the listed 5. I hope that makes sense.
Ended up going with the below.
String[] words = {"ff", "sf", "fb", "sb", "pause"};
List<String> validList = Arrays.asList(words);
String checkInput = lower;
for (String value : checkInput.split( "," ))
{
if( !validList.contains( value ) )
{
throw new Exception("Invalid mode specified: " + modes);
}
}
I’m no regex wiz, but if you look at each value individually, it could give you much better control on how to report errors, and lets you decide to reject the whole input or just remove the invalid entry.