Home > Enterprise >  Negative Version of given regex needed (JS)
Negative Version of given regex needed (JS)

Time:10-31

Again and again Regex... Can please someone show me how to got the negative lookahead working with the given regex here: https://regex101.com/r/kS6wUh/1

The Regex looks like this: ^\b[A-Z] |_ ?[A-Z]

Target would be to check if a given string contains only Characters A-Z or _

Invalid_TEXT (invalid)
all_in_small_invalid (invalid)
INVALID-DASH (invalid)
VALID_KEY (valid)
ANOTHER_VALID_KEY (valid)
 (empty --> invalid)

The regex should match on invalid my current returns the valid matches.

I have no clue where to add (?!...) in my current version because all options I've tried ended up either by getting a regex error or counting everything. I think my regex has not the correct structure for a negative lookahead.

CodePudding user response:

You only have to test if one or more characters in the string are not of the set [A-Z_], which is done by inserting a caret. So [^A-Z_]. Demo

const strs = `Invalid_TEXT
all_in_small_invalid
INVALID-DASH
VALID_KEY
ANOTHER_VALID_KEY
 (empty)`.split(`\n`);
 
strs.forEach(str => console.log(str, /[^A-Z_]/.test(str) ? `Not ok` : `OK`));
 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related