-1

I need to search multiple words in each line and if all the words are matching in a line then print that line.

file.txt

This is starting string.
This is starting but different string.
This is starting but the same string.
This is a differnet string.
This is a old string.

i have done in below manner.

import re
with open("file.txt", "r") as in_file:
    for line in in_file:
        if (re.search('different',line)) and (re.search('string',line)):
            print line

But i need something like:

if (re.search('different' and 'string',line))::
            print line

I know we have or as we use

if (re.search('different'|'string',line))::
                print line

Can anybody help me to use 'and' in similar manner.

PAR
  • 624
  • 1
  • 5
  • 16

2 Answers2

1

You don't need to use module re in here, in operator will do the job for ya.

if 'different' in line and 'string' in line:
sbbs
  • 1,450
  • 2
  • 13
  • 20
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • Thank you. I was having idea on this, that's why i tried the same in regex also and added to my post. Anyhow all(x in line for x in ['different', 'string']) has done complete job to me. Thank you once again. – PAR Apr 27 '17 at 08:18
1

In your case there is no need to use regexp, you can just do 'string' in line and 'different' in line, or all(x in line for x in ['different', 'string'])

Darth Kotik
  • 2,261
  • 1
  • 20
  • 29