Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match all capital and underscore

Tags:

regex

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.

like image 303
Xaree Lee Avatar asked Apr 05 '17 07:04

Xaree Lee


People also ask

How do you match a capital letter in regex?

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.

What is Alnum in regex?

The Alphanumericals are a combination of alphabetical [a-zA-Z] and numerical [0-9] characters, 62 characters.

Is underscore a special character in regex?

Regex doesn't recognize underscore as special character.


1 Answers

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
like image 194
Wiktor Stribiżew Avatar answered Sep 28 '22 04:09

Wiktor Stribiżew