Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalized Words with Regular Expression

Tags:

regex

I'm new to RegEx and I'm looking for a way to match sentences where the first letter is capitalized and the rest is in lowercase.

I've tried a couple of things (IF statements included), but just can't seem to get it.

This is my last version:

(([A-Z])([a-z]+\s|[a-z]+))+

I thought it worked at first, but is now accepting capitalized letters in the middle of the word.

The Output Would Be Like This (Each Word Capitalized).

Thanks!!

like image 507
Manuel Campos Avatar asked Jul 21 '26 22:07

Manuel Campos


2 Answers

To match whole strings that start with an uppercase letter and then have no uppercase letters use

^[A-Z][^A-Z]*$

See the regex demo. ^ matches the start of string, [A-Z] matches the uppercase letters, [^A-Z]* matches 0 or more chars other than uppercase letters and $ matches the end of string.

To match capitalized words, you may use

\b[A-Z][a-zA-Z]*\b

where \b stands for word boundaries. See the regex demo.

In various regex flavors, there are other ways to match word boundaries:

  • bash,r (TRE, base R): \<[A-Z][a-zA-Z]*\>
  • postgresql, tcl: \m[A-Z][a-zA-Z]*\M or \y[A-Z][a-zA-Z]*\y
  • bash, mysql (MySQL versions before 8): [[:<:]][A-Z][a-zA-Z]*[[:>:]]

Also, you may consider using [[:upper:]] or \p{Lu} instead of [A-Z] and [[:alpha:]] or \p{L} instead of [a-zA-Z] to match any Unicode uppercase letters or any letters correspondingly.

See this demo and this demo, too.

like image 108
Wiktor Stribiżew Avatar answered Jul 23 '26 19:07

Wiktor Stribiżew


The expression accepts capital letters in the middle of the world because now the spaces between words are optional, and words can run into each other.

You can take a more structured approach: a sentence must have at least one word. That's

[A-Z][a-z]*

After that initial word you can get any number of more words, each preceded by whitespace. So in total:

[A-Z][a-z]*(\s[A-Z][a-z]*)*
like image 39
Joni Avatar answered Jul 23 '26 18:07

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!