vgoklani vgoklani - 4 years ago 114
Python Question

regex for catching only upper-case matches

I need to write a regex that will catch hashtags with capital letters and apostrophes only.

For example, "#([A-Z']+)" will catch "#IS" from the following example:

#IS your glass half-full or half-empty?


BUT unfortunately will also catch "#I" in this example

#Is your glass half-full or half-empty?


I tried this: "#([A-Z]+[^a-z]+)" but it catches "#II"

#IIs your glass half-full or half-empty?


I use python and there are other clever ways of solving this problem, but I would prefer a regex solution

Answer Source

Use \b to indicate a word boundary. Then only entire capitalized words that start with a # and potentially contain an ' will be matched:

"((\s|^)#[A-Z']+\b)"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download