Uthman
Uthman

Reputation: 9807

Regex not to allow double underscores

Trying to apply regex for not allowing a string with double underscores

 [a-z][a-z0-9_-]+[^__]

but its failing in many cases like:

ab_      doesn't matches whereas it should
ab__c_   matches whereas it shouldn't.

Upvotes: 8

Views: 6925

Answers (3)

João Silva
João Silva

Reputation: 91309

[^__] matches one character that is not underscore. To assert that your string doesn't have two consecutive underscores, you could use a negative lookahead:

^(?!.*__.*)[a-z][a-z0-9_-]+$

The lookaround asserts that your string does not have two consecutive underscores (?!.*__.*), and then matches your required string if the assertion does not fail -- [a-z][a-z0-9_-]+.

Upvotes: 10

xhudik
xhudik

Reputation: 2444

in perl it would be:

    if($a =~ /__/){
    } else{
    }

which means if string a contains "__" do something, if not do something else. Of course there is many ways how to beutify such code

Upvotes: 1

Hachi
Hachi

Reputation: 3289

the [^] syntax defines a set of characters so that it matches a character not present in this set

if you want to match two characters that are not underscores you can use [^_]{2}

but if you really want to check if a string has two underscores, you better search for two underscores and negate the result

for example in perl: "ab_" !~ /__/

Upvotes: 1

Related Questions