Xaree Lee
Xaree Lee

Reputation: 3387

Regex to match all capital and underscore

I need a Regex to test a string whether match the follow rules:

  1. Contains at least a word (could be only a character)
  2. All characters should be capital.
  3. Use one, and only one, underscore (_) 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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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 anchor

Upvotes: 12

Related Questions