0

I am trying to match a text in a file

In [44]: with open(path) as f:
   ....:     for line in f:
   ....:         matched = re.search('^PARTITION BY HASH',line)
   ....:         if matched is not None:
   ....:             print matched.group()
   ....:

The file contains lines like PARTITION BY HASH(SOME_THING); And also some other lines among which there is SUBPARTITION BY HASH(SOME_THING) which shouldn't be matched

After the match i would like to delete that line. But the print matched.group fails why ?

2
  • 8
    why re here? just do if "PARTITION BY HASH" in line or if line.startswith("PARTITION BY HASH"): Commented Nov 6, 2012 at 10:17
  • Updated my question on why i should be using a regex Commented Nov 6, 2012 at 10:26

2 Answers 2

1

something like this:

In [29]: strs1="PARTITION BY HASH(SOME_THING)"

In [30]: strs2="SUBPARTITION BY HASH(SOME_THING)"

In [31]: bool(re.match(r"^PARTITION BY HASH",strs1))
Out[31]: True

In [32]: bool(re.match(r"^PARTITION BY HASH",strs2))
Out[32]: False
Sign up to request clarification or add additional context in comments.

Comments

0

But the print matched.group fails

Well it simply does what it is supposed to do: it returns the match. In this case since

>>> import re
>>> line = "PARTITION BY HASH(something)"
>>> re.search('^PARTITION BY HASH', line).group()
'PARTITION BY HASH'

If you want to print the lines that start with 'PARTITION BY HASH', based on what Ashwini Chaudhary suggested:

with open(path) as f:
    for line in f:
        if line.startswith('PARTITION BY HASH'):
            print line,

Please note the comma to prevent print from inserting an additional end-of-line characters.

If you insist on using the package re

import re

with open(path) as f:
    for line in f:
        if re.match('PARTITION BY HASH', line):
            print line,

Please note the usage of re.match without the starting position indicator ^ (see http://docs.python.org/2/library/re.html#search-vs-match for more information)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.