0

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);
        }
       }
1
  • 1
    could you tell us what you've tried? Commented Oct 14, 2011 at 18:16

6 Answers 6

2

You can store your legal values in an HashSet, for example, and use the contains() method to check if a particular value is in the list:

HashSet<String> legalVals = new HashSet<String>();

legalVals.add("FF");
legalVals.add("SF");
//etc

String valToCheck = "FfdsG";

if (legalVals.contains(valToCheck)) { //False
  print "Value found: " + valToCheck;
} else {
  print "Bad value: " + valToCheck;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would use HashSet over ArrayList. It will be much faster at performing the contains check, especially for long lists of legal values.
Oops, forgot to change in the code section. Thank you, masked stranger!
it seems regardless of what i enter as input it always returns as "bad value".
1
(?<=(^|,))(?!((FF|SF|FB|SB|Pause)(?=(,|$))))

If text matches with this regex, then it contains wrong value. This regex doesn't match with any text, it uses only assertions and detects position where the wrong text starts. If you want to get the first occurence of the wrong text:

(?<=(?:^|,))(?!(?:(?:FF|SF|FB|SB|Pause)(?=(?:,|$))))([^,]*)

the first captured group will contain it.

Comments

0

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.

public class InputCleaner
{
    private final static List<String> allowedEntries = Arrays.asList( new String[] { "FF", "SF", "FB", "SB", "Pause" } );

    public static void main( String[] args ) throws Exception
    {
        String input = "FF,SF,FB,SB,FF,Pause";
        String input2 = "FF,SF,FB,SB,FfdsG,FF,Pause";

        validateInput( input );
        validateInput( input2 );
    }

    private static void validateInput( String input ) throws Exception
    {
        for (String value : input.split( "," ))
        {    
            if( !allowedEntries.contains( value ) )
            {
                throw new Exception( "Found a bad input value! " + value );
            }
        }

        System.out.println( "Input string clean:" + input );
    }
}

1 Comment

Sorry but " throws Exception" is one of the most disgusting things I've seen.
0

Not sure what you want. For the regex below, matches() will return true if all the strings are good and false if there are one or more bad strings. This regex allows any amount of whitespace at the beginning or end of the strings. Also, multiple commas are ignored. For example, " FF , SF ,,,,,,,,Pause " is a match. Remove the "\s*" from the regex to disallow whitespace.

(\s*(FF|FB|SF|SB|Pause)\s*,*)+

Check out this online regex tool

Comments

0
inputString.matches("FF|SF|FB|SB|Pause")

assuming you've already split your comma separated string input and inputString is one element in that split array.

Comments

0

Yes, Java has fine regex support and it's easy enough to use the "OR" operator in your regex to do what you want to do. Something like this should illustrate the point:

package exp;

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {

  public static void main(String[] args){

    Pattern pattern = Pattern.compile("FF|SF|FB|SB|Pause");

    Matcher matcher =  pattern.matcher( "FfdsG" );

    if (matcher.matches()) {
        System.out.printf("I found the text \"%s\" starting at " +
           "index %d and ending at index %d.%n",
            matcher.group(), matcher.start(), matcher.end());
    }
    else {
        System.out.printf("No match found.%n");
    }
    
    
    matcher = 
        pattern.matcher( "FF" );
    
        if (matcher.matches()) {
            System.out.printf("I found the text \"%s\" starting at " +
               "index %d and ending at index %d.%n",
                matcher.group(), matcher.start(), matcher.end());
        }
        else {
            System.out.printf("No match found.%n");
        }       
    

    matcher = 
        pattern.matcher( "Pause" );
    
        if (matcher.matches()) {
            System.out.printf("I found the text \"%s\" starting at " +
               "index %d and ending at index %d.%n",
                matcher.group(), matcher.start(), matcher.end());
        }
        else {
            System.out.printf("No match found.%n");
        }           
    
}

}

When you run this, you'll get this output:

No match found.

I found the text "FF" starting at index 0 and ending at index 2.

I found the text "Pause" starting at index 0 and ending at index 5.

So, just take your comma separated string, loop over the entries and use the matcher.

Or you can probably construct an even more complicated regex that will let you leave the commas in and still get the desired output. Check the many various regex tutorials for more on that point...

Note that the split method on String will let you easily separate the discrete values in the original comma separated string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.