Regex: uppercase words that don´t start with a hyphen

Viewed 50

I need to match all uppercase words that don't start with a hyphen.
There are multiple uppercase words in each line.

examples:

,BOAT -> match
BANANA, -> match
WATER -> match
-ER -> no match because of hyphen

Thanks in advance :)

2 Answers

I need to match all uppercase words that don't start with a hyphen.

You may use this regex:

(?<!\S)[^-A-Z\s]*[A-Z]+

RegEx Demo

RegEx Explained:

  • (?<!\S): Make sure we don't have a non-space before current position
  • [^-A-Z\s]*: Match 0 or more of any characters that are not hyphen and not uppercase letters and not whitespaces
  • [A-Z]+: Match 1+ uppercase letters

You can use

\b(?<!-)[A-Z]+\b
\b(?<!-)\p{Lu}+\b

See the regex demo

Details:

  • \b - word boundary
  • (?<!-) - a negative lookbehind that fails the match if there is a - immediately to the left of the current position
  • [A-Z]+ / \p{Lu}+ - one or more uppercase letters (\p{Lu} matches any uppercase Unicode letters)
  • \b - word boundary.
Related