Reputation: 3387
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
.
Upvotes: 13
Views: 10673
Reputation: 627103
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 anchorUpvotes: 12