I need a Regex to test a string whether match the follow rules:
_
) between each word pairs (e.g. HELLO_WOLRD
)The test values (valid and invalid):
const validConstants = [
'A',
'HELLO',
'HELLO_WORLD',
];
const invalidConstants = [
'', // No empty string
'Hello', // All be Capitals
'Add1', // No numbers
'HelloWorld', // No camel cases
'HELLO_WORLD_', // Underscores should only be used between words
'_HELLO_WORLD', // Underscores should only be used between words
'HELLO__WORLD', // Too much Underscores between words
];
I tried ^[A-Z]+(?:_[A-Z]+)+$
, but it fails in A
and HELLO
.
Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.
The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.
Regex doesn't recognize underscore as special character.
You need a *
quantifier at the end:
^[A-Z]+(?:_[A-Z]+)*$
^
The (?:_[A-Z]+)*
will match zero or more sequences of _
and 1 or more uppercase ASCII letters.
See the regex demo.
Details:
^
- start of string anchor[A-Z]+
- 1+ uppercase ASCII letters (the +
here requires at least one letter in the string)(?:_[A-Z]+)*
- a non-capturing group matching zero or more sequences of:
_
- an underscore[A-Z]+
- 1+ uppercase ASCII letters (the +
here means the string cannot end with _
)$
- end of string anchorIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With