How to match complete words for acronym using regex?

by giovanny.lueilwitz , in category: Third Party Scripts , a month ago

How to match complete words for acronym using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a month ago

@giovanny.lueilwitz 

To match complete words for an acronym using regex, you can use boundary anchors () to ensure that the acronym is a standalone word and not part of a larger word. For example, if you want to match the acronym "ABC", you would use the following regex pattern:


ABC


This pattern will match the complete word "ABC" as a standalone word, but not if it is part of a larger word such as "ABCD" or "ABCDEF".


Here is an example of how you can use this regex pattern in Python to match complete words for an acronym:

1
2
3
4
5
6
7
8
import re

text = "I work at the ABC company and earn a lot of money."
pattern = r'ABC'
matches = re.findall(pattern, text)

for match in matches:
    print(match)


This will output:

1
ABC


This code snippet will find and print the complete word "ABC" from the text, ignoring any other occurrences where it is not a standalone word.