Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Negating Regular expressions

Status
Not open for further replies.

TobyToo

Technical User
Sep 11, 2004
4
GB
In Python, how can one negate an overall regular expression? For example, the regex ...

import re
string='This is a test'
string2='Test too BC '
re.search('[ ][A-Z][A-Z][ ]',string)
<doesn't match>
re.search('[ ][A-Z][A-Z][ ]',string2)
<DOES match>
... but what if I want to match only strings that *don't* have two (and only two) adjacent capital letters?

I tried ...
re.search('[^([ ][A-Z][A-Z][ ])]',string2)
.. but only got a 'mismatch of parentheses' error

Thanks for your help in advance!
 
Are you trying to return the string or simply test for the match? If search doesn't find the expression, then it returns None, so you can say if ! re.search( ..., string ) and you will know that the string didn't match.
 
I actually want to return the string, so in this case ! re.search ... wouldn't help me (well that's not entirely true - I might include a check-box on the GUI front end so the user can specify whether to iclude or exclude the expression. Nevertheless, it would be nice to know a general solution).
 
I don't think there is a general solution, what you're doing goes against the design of regexps. They are designed to match an expression and return it. I could be wrong, it's been known to happen, I'd recommend O'Rielly's book on regular expressions.

Besides, you have the string, it's the second argument to the function. Don't be one of those programmers that spends 2 days trying to figure out how to eliminate 2 lines of code.
When you have to support the code in six months you'll appreciate the readability.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top