2

I'm trying to find the regex expression that validates a specific rule, but I'm quite a beginner with regular expressions.

Rule

  • There can be any number of words
  • Words are space-separated
  • Words only contain letters
  • Words start with a capital
  • The last word must be a single capitalized character

Expression

Here is where I am so far: ([A-Z][a-z]+[ ]*)*[A-Z]

Examples

Match

  • Example Name A
  • A New Example C

No match

  • a Test B
  • Wrong Name
  • Another_Wrong_Name A
  • Nop3 A
Munshine
  • 402
  • 3
  • 14

1 Answers1

1

Notes:

  • Your regex matches words with two or more letters only before the final one-letter word. You need to match one or more letter words using [A-Z][a-z]*
  • You use a character class, [ ], to match a single space, and this is redundant, remove brackets.
  • You need to match the entire string, with anchors, ^ and $, or \A and \z/\Z (depending on regex flavor).

You can use

^([A-Z][a-z]* )*[A-Z]$
^(?:[A-Z][a-z]* )*[A-Z]$
^(?:[A-Z][a-z]*\h)*[A-Z]$
^(?:[A-Z][a-z]*[^\S\r\n])*[A-Z]$

Note [^\S\r\n] and \h match horizontal whitespace, not just a regular space.

The non-capturing group, (?:...), is used merely for grouping patterns without keeping the text they matched in the dedicated memory slot, which is best practice, especially with repeated groups.

See this regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563