Tiny
Tiny

Reputation: 27899

Regular expression (regex) in JavaScript

I need a regex that can validate a string in the following criteria.

Accordingly, the following regex works in Java.

(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})

But in JavaScript, a string like ROLE_ADMIN_s (s at the end in small case) is treated as a valid string that shouldn't actually be. The maximum allowable characters (20) are also not validated correctly.

I'm using the match() function like,

if($("#txtAuthority").val().match("(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})"))
{
     //...
}

Upvotes: 0

Views: 140

Answers (1)

Gumbo
Gumbo

Reputation: 655239

Java’s matches method expects the pattern to match the whole string while JavaScript’s match method is rather a find any match method as it suffices that the pattern is found somewhere inside the string.

"ROLE_ADMIN_s".match(/(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})/)[0] === "ROLE_ADMIN_"

If you want JavaScript’s match to act like Java’s matches, use anchors for the begin (^) and end ($) of the string:

/^(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})$/

This will fail on your string:

"ROLE_ADMIN_s".match(/^(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})$/) === null

Upvotes: 1

Related Questions