Home > OS >  how to do replacement of mulile string with multiple values in regex python
how to do replacement of mulile string with multiple values in regex python

Time:10-26

Given the following string: """ All I want is a proper cup of coffee Made in a proper copper coffee pot I may be off my dot But I want a cup of coffee From a proper coffee pot Tin coffee pots and iron coffee pots They’re no use to me If I can’t have a proper cup of coffee In a proper copper coffee pot I’ll have a cup of tea. """ Using regular expressions, i need to write a function that highlight the words “coffee”,“pot” or “pots” if they appear at the end of a line so the patter i tried is coffee$|pot$|pots$ ( since $ is used for endwith)

if i do in regex101 it s highlighting all the required words

hoewever output in jupyter notebook is

'All I want is a proper cup of coffee\nMade in a proper copper coffee pot\nI may be off my dot\nBut I want a cup of coffee\nFrom a proper coffee pot\nTin coffee pots and iron coffee pots\nThey’re no use to me\nIf I can’t have a proper cup of coffee\nIn a proper copper coffee pot\nI’ll have a cup of tea'

i tried with coffee$ coffee$\n coffee\n$ nothing works here. if i use .replace("\n", " ") it its taking as whole string. how to handle \n in jupyter notebook

enter image description here tried in regex101

CodePudding user response:

I'm not sure what you mean by "highlight", but here's an example of a RegEx that matches all instances "coffee", "pot", and "pots" at the end of a line:

import re

string = """
All I want is a proper cup of coffee
Made in a proper copper coffee pot
I may be off my dot
But I want a cup of coffee
From a proper coffee pot
Tin coffee pots and iron coffee pots
They’re no use to me
If I can’t have a proper cup of coffee
In a proper copper coffee pot
I’ll have a cup of tea.
"""

pattern = re.compile(r'(coffee|pots?)(?:\n)')
print(re.findall(pattern, string))

See here for a breakdown of the RegEx pattern used.

  • Related