Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: per Dhruv's comments, allowing spaces and single quotation marks (aka apostrophe). neither are special characters regex, so it should be okay

...

Code Block
bgColor#ccccff
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class FilteredLog {
    private static final StringBuilder logBuffer = new StringBuilder();
    private static String log = logBuffer.toString();
    
    public static Set<String> suggestSearches(String search) {
        Set<String> searches = new HashSet<String>();
        
        // Filter user input
        StringBuilder sb = new StringBuilder(search.length());
        for (int i = 0; i < search.length(); ++i) {
            char ch = search.charAt(i);
            if (Character.isLetterOrDigit(ch) ||
                    ch == ' ' ||
                    ch == '\'') {
                sb.append(ch);
            }
        }
        search = sb.toString();
        
        // Construct regex from user string
        String regex = "^(" + search + ".*),[0-9]+?,[0-9]+?$";
        int flags = Pattern.MULTILINE;
        Pattern keywordPattern = Pattern.compile(regex, flags);
        
        // Match regex
        Matcher logMatcher = keywordPattern.matcher(log);
        while (logMatcher.find()) {
            String found = logMatcher.group(1);
            searches.add(found);
        }
        
        return searches;
    }
    
    private static void append(CharSequence str) {
        logBuffer.append(str);
        log = logBuffer.toString(); //update log string on append
    }

    static {
        // this is supposed to come from a file, but its here as a string for
        // illustrative purposes
        append("Alice,1267773881,2147651408\n");
        append("Bono,1267774881,2147351708\n");
        append("Charles,1267775881,1175523058\n");
        append("Cecilia,1267773222,291232332\n");
    }
}

...