0

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

  • Beginning with the verbatim text ROLE_.
  • Only a combination of capital letters and undescores are allowed.
  • Must have minimum of 6 and maximum of 20 characters in it.
  • Two or more consecutive underscores are disallowed.
  • Leading and/or trailing underscores are disallowed.
  • The text ROLE_ADMIN is disallowed.

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})"))
{
     //...
}
2
  • 2
    You need to add ^ to the start and $ to the end. Also, it's not your issue because the browser handles it automatically in this case, but you should wrap regexps in /myexpression/ instead of "myexpression" Commented May 5, 2013 at 16:18
  • :-) I had reverse trouble while moving from js to java - adding .* at start & end... Commented May 5, 2013 at 16:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

/^(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})$/ evaluates to false on valid strings like - ROLE_ADMIN_S.
This works when I remove the forward slash / from both sides of the expression like ^(?!.*__.*)(?!^ROLE_ADMIN$)(?!.*_$)(ROLE_[A-Z_]{1,15})$. I don't get it correctly.
@Tiny In JavaScript, RegExp objects have a literal syntax that is /<pattern>/<flags>. Of course, if you use those literals as a string, i.e. "/<pattern>/<flags>", the delimiters / are also treated as part of the pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.