user15354331
user15354331

Reputation:

RegEx to find a keyword & print whole line with matches

I need to create a regexp to be used in python where a keyword is to be matched in output & whole line with exact matches should be displayed, kindly assist

Some_output = "hello how are you something. \nhello how are you2 something.\nhello how are you3 
something."
Search_String ="you2"
Expected Output - how are you2 something.
vv = re.findall(r'.*you2.*',Some_output)
print(vv)  - returns nothing 

Upvotes: 0

Views: 1083

Answers (2)

mhhabib
mhhabib

Reputation: 3121

First, convert the string into a list then find any line matches with Search_String tag.

Some_output = "hello how are you something. \nhello how are you2 something.\nhello how are you3 something."
LINES = Some_output.split('\n')
Search_String = "you2"
for LINE in LINES:
    if re.search(r'\b{}\b'.format(Search_String), LINE):
        print(LINE)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

I would tokenize/split your input into a list of sentences, then use a list comprehension to find matching sentences:

inp = "hello how are you something. \nhello how are you2 something.\nhello how are you3 something."
sentences = inp.split('\n')
search = 'you2'
matches = [s for s in sentences if re.search(r'\b' + search + r'\b', s)]
print(matches)  # ['hello how are you2 something.']

Upvotes: 1

Related Questions