python – Regex: Find words that have a O in second position AND end in IONS
The other day, I was trying to teach the principles of Regex to a student – I am far from an expert but wanted to show the principles of it. I have a text file containing all the words of the English language, and I wanted to define a series of rules in regex so that the only word that would come out would be “CONGRATULATIONS”.
We did it in Python code first, then using the re python library. The two first rules were to find words having O as the second letter, and words ending in IONS.
While we first tried to find the words matching a rule and then the other in pure Python, we tried to do it in one go using the regex pattern ^.O[A-Z]*IONS$. We were surprised to see that the two methods differed by one word: IONS.
I mean, it totally makes sense, as the regex pattern is looking, by definition, for words of at least 6 characters. But it got us wondering if there was a way to get the words that have O as a second letter, which can also be the O of IONS in one single regex pattern.
I know we can totally do it in two steps, first getting the words having an O as the second letter, and then getting the words ending in IONS among these words, but I just wondered if it was possible in one step alone.
Thanks 🙂
Read more here: Source link
