Home > database >  regex for one Capital
regex for one Capital

Time:03-06

Can someone please give me a piece of advice on how to build a regex for the following conditions -- only one capital letter in a word (must be one) and no digits.

  • example pass -- Apple aPple giFt
  • example decline -- street agentORANGE sequence1122

CodePudding user response:

You can look for letters, with a positive lookahead for only 1 uppercase letter.

So to find such words in a text :

\b(?=\p{Ll}*\p{Lu}\p{Ll}*\b)\p{L} \b

To match a complete string :

^(?=\p{Ll}*\p{Lu}\p{Ll}*$)\p{L} $

CodePudding user response:

A Word is really undefined.
The boundary's are undefined.

Word being the regex \w construct (not a language word):
\b[^\W\p{Lu}\p{Nd}]*\p{Lu}[^\W\p{Lu}\p{Nd}]*\b
https://regex101.com/r/YV5wUc/1

 \b                   # Boundary
 [^\W\p{Lu}\p{Nd}]*   # Optional Non-Uppercase or digit Word characters
 \p{Lu}               # Upper case Letter
 [^\W\p{Lu}\p{Nd}]*   # Optional Non-Uppercase or digit Word characters
 \b                   # Boundary

Its all based on the interpretation of what is your meaning of word
and of boundarys.
Literally many ways to do this, but all will follow the format above.

  • Related