Regular Expression Performance: Validating Alphanumeric Characters

When trying to verify that a string consists of only alphabetic characters, I get two possible solutions to regular expressions.

The first checks that each character in the string is alphanumeric:

/^[a-z]+$/

The second tries to find a character somewhere in a non- alphanumeric string :

/[^a-z]/

(Yes, I could use character classes here.)

Is there a significant performance difference for long lines? (Anyway, I assume the second option is faster.)

+5
source share
2 answers

Just by looking at it, I would say that the second method is faster.

However, I did a quick, unscientific test, and the results are apparently inconclusive:

.


P.S. . , .

+4

Perl:

    @testStrings = qw(asdfasdf asdf as aa asdf as8up98;n;kjh8y  puh89uasdf ;lkjoij44lj 'aks;nasf na ;aoij08u4 43[40tj340ij3 ;salkjaf;  a;lkjaf0d8fua ;alsf;alkj   
a a;lkf;alkfa as;ldnfa;ofn08h[ijo ok;ln n ;lasdfa9j34otj3;oijt 04j3ojr3;o4j ;oijr;o3n4f;o23n a;jfo;ie;o ;oaijfoia ;aosijf;oaij ;oijf;oiwj; 
qoeij;qwj;ofqjf08jf0 ;jfqo;j;3oj4;oijt3ojtq;o4ijq;onnq;ou4f ;ojfoqn;aonfaoneo ;oef;oiaj;j a;oefij iiiii iiiiiiiii iiiiiiiiiii); 


    print "test 1: \n";
    foreach my $i (1..1000000) {
            foreach (@testStrings) {
                    if ($_ =~ /^([a-z])+$/) {
                            #print "match"
                    } else {
                            #print "not"
                    }
            }
    }

    print `date` . "\n";

    print "test 2: \n";
    foreach my $j (1..1000000) {
            foreach (@testStrings) {
                    if ($_ =~ /[^a-z]/) {
                            #print "match"
                    } else {
                            #print "not"
                    }
            }
    }

: ; & ; perl_file > ;

100% , . Regex 10 11 , Regex 8 .

+2

All Articles