Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I like grep -v. I use it all the time. But I am also doing some text processing in python, and there is one crucial thing that I lack.

Usually, I use grep -v to take extraneous stuff out of text.

For instance,

$grep -v [a-z]
(confirms that I don't want those lines)
$grep [a-z] > linesiwanted

But how do I match the complement of a regex in Python? For instance, the complement of \w?

share|improve this question
    
see stackoverflow.com/questions/164414/… –  Sirex Feb 23 '12 at 15:53

2 Answers 2

up vote 8 down vote accepted

A regex in Python, either the search or match methods, returns a Match object or None. For grep -v equivalent, you might use:

import re
for line in sys.stdin:
    if re.search(r'[a-z]', line) is None:
        sys.stdout.write(line)

Or more concisely:

import re; sys.stdout.writelines([line for line in sys.stdin if re.search(r'[a-z]', line) is None])
share|improve this answer
    
+1 the SO link in the comment mentions negative-lookahead assertions but to be honest i think your snippet is much more sensible and elegant. thanks. –  ixtmixilix Feb 24 '12 at 0:58
    
it turns out you can also use [^a-z] to match the complement of the set [a-z] –  ixtmixilix Feb 24 '12 at 12:29

It turns out you can just use [^a-z] to mean grep -v [a-z].

I'm using it like:

#!/usr/bin/env python
# coding=UTF-8

import sys, re

for file in sys.argv[1:]:
    f = open(file)
    string = f.read()
    regex = re.compile('[^a-z]')
    subs = regex.sub('', string)
    f.close()
    print subs
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.