Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate string against a character set?

Assume any given string: how can I validate it against a predefined character set? I'd like to use ASCII 65-90 (A-Z), 33 (!), 36 ($), 38 (&), 63 (?).

Would I have to apply regex on the full string? Or is it better to read the string char by char, and match the Integer on the predefined range?

String test = "ASDQWE!&";
for (int i = 0; i < test.length; i++) {
        int num = (int) val.charAt(i);
        //TODO validate
}
like image 867
membersound Avatar asked Sep 13 '26 20:09

membersound


2 Answers

Use a unicode character range corresponding to ASCII 65-90:

String test = "ASDQWE!&";
if (test.matches("[\u0041-\u005A]*")) {
    System.out.println("match!");
}

Your sample string actually isn't a match for ASCII 65-90, but ASDQWE, without the punctuation at the end, is.

Demo

like image 147
Tim Biegeleisen Avatar answered Sep 16 '26 09:09

Tim Biegeleisen


I was curious and decided to benchmark it with JMH; here's what I found:

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(3)
public class MyBenchmark {

    @Param({"ASDQWE!&"})
    private String test;

    private static final Pattern PATTERN = Pattern.compile("[A-Z!$&?]*");

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
    }

    @Benchmark
    public boolean oldMethod() {
        for (int i = 0; i < test.length(); i++) {
            int c = test.charAt(i);

            if (c >= 65 && c <= 90) {
                continue;
            }

            switch (test.charAt(i)) {
                case 33:
                case 36:
                case 38:
                case 63:
                    break;
                default:
                    return false;
            }
        }
        return true;
    }

    @Benchmark
    public boolean newMethod() {
        return PATTERN.matcher(test).matches();
    }
}

And its results:

Benchmark                (test)  Mode  Cnt   Score   Error  Units
MyBenchmark.newMethod  ASDQWE!&  avgt   30  55.848 ± 1.275  ns/op
MyBenchmark.oldMethod  ASDQWE!&  avgt   30  14.586 ± 0.034  ns/op

Even with compiling a pattern, it's clear that iterating over the String will be faster, but it's definitely more readable when using a regular expression.

like image 33
Jacob G. Avatar answered Sep 16 '26 10:09

Jacob G.