-1

I need a help,

 list1 = [abc, xyz]

output:

123
143
153
abc!
abc
hhj
xyz--
xyz

I am using below code:

 for line in ouput.split("\n"):
    line = line.strip()

    if (re.search(list1, line)):
        print "abc and xyz present in output"

Above code does not work for my requirement

Note it should not macth for abc! and xyz-- meaning it must match only abc and xyz

Bittu
  • 31
  • 2
  • 9
  • 2
    I don’t get what you’re trying to do, please provide a **minimal complete verifiable example**, with a sample input and the desired output. – Taku Jun 16 '17 at 04:20
  • https://stackoverflow.com/q/4843158/6619424 – Arun Jun 16 '17 at 04:25
  • The `re.search` method should take a regular expression as its first parameter. – Poosh Jun 16 '17 at 04:26

3 Answers3

0

Although your question is pretty unclear and lacks a mcve. If you want to check possession, if line is the same as something inside list1, you can just use the in operator.

if line in list1:
    print "abc or xyz present in output"

In your case, it should match twice, once for abc and once for xyz. Since you said:

Note it should not macth for abc! and xyz--

Note: regex is for searching patterns in a string. Not very appropriate for your task.

Taku
  • 31,927
  • 11
  • 74
  • 85
  • because i want match only abc and not abc! if i use above method it will match abc! as well . – Bittu Jun 16 '17 at 04:57
  • No, it won’t. Have you tried it? Btw, `list1 = ["abc", "xyz"]` there’s quotes to define string – Taku Jun 16 '17 at 04:57
0

guesing you want to search each output line is in list1 or not! check this out you don't need regex

list1 = ['abc', 'xyz']
output='''123
143
153
abc!
abc
hhj
xyz--
xyz'''

for line in output.split("\n"):
    line = line.strip()
    if line in list1:
        print line,"present in output"

output:

abc present in output
xyz present in output

DexJ
  • 1,264
  • 13
  • 24
0

If you still want to use regex you can use this:

import re

output = """123
143
153
abc!
abc
hhj
xyz--
xyz"""

print(output)

for line in output.split("\n"):
    line = line.strip()
        if re.search(r"^\babc\b$", line) or re.search(r"^\bxyz\b$", line):
        print('line matched: {}'.format(line))

However, I would create a separate dictionary and look for the matches in there:

keywords = {'abc' : 0, 'xyz' :0, ...}

for line in output.split("\n"):
    if line in keywords:
        print('line matched: {}'.format(line))

Dictionary makes sense if you have a lot of keywords and they are all unique and your output file contains a lot of lines. The lookup time will be constant O(1).

If you use list of keywords the lookup will be O(n) which in total make your algorithm O(n^2).

Nurjan
  • 5,889
  • 5
  • 34
  • 54