yosemite
yosemite

Reputation: 137

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

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 :)

Upvotes: 2

Views: 58

Answers (2)

anubhava
anubhava

Reputation: 785156

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

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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.

Upvotes: 1

Related Questions