RegEx for matching brackets
NevilleDNZ
nevillednz at gmail.com
Fri May 2 18:51:16 EDT 2008
On May 2, 11:13 am, George Sakkis <george.sak... at gmail.com> wrote:
> [1]http://en.wikipedia.org/wiki/Context-free_language
> [2]http://en.wikipedia.org/wiki/Regular_language
> [3]http://wiki.python.org/moin/LanguageParsing
Thanx for the link to these parsers. ANTLR looks interesting.
Yoyo: http://www-users.cs.york.ac.uk/~fisher/software/yoyovwg/readme
I figured out a way to do it in python.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
tests="""
{ a test BAD
{ a test } OK
{ a test } { a test } OK
{ a test } { this { a test } is a test } OK
{ a test { this { a test } is a test } missing close BAD
a test } { this { a test } is a test } BAD
{ a test } this { a test } is a test } BAD
""".splitlines()[1:]
def referee(str):
return bool(re.search("OK",test))
def check_open_close(str):
try:
eval("".join({"{":"[","}":"],"}[c] for c in re.findall( "([{}])|(?:
[^{}]+)", str) if c))
except SyntaxError:
return False
else:
return True
for test in tests:
if check_open_close(test) == referee(test):
print "DETECTED:",test
else:
print "MISSED:",test
[linux]$ ./matchall_open_close.py
DETECTED: { a test BAD
DETECTED: { a test } OK
DETECTED: { a test } { a test } OK
DETECTED: { a test } { this { a test } is a test } OK
DETECTED: { a test { this { a test } is a test } missing close BAD
DETECTED: a test } { this { a test } is a test } BAD
DETECTED: { a test } this { a test } is a test } BAD
It's not exactly what I planned, but as a python one/two-liner it
works fine.
eval("".join({"{":"[","}":"],"}[c] for c in re.findall( "([{}])|(?:
[^{}]+)", str) if c))
ThanX again
N
More information about the Python-list
mailing list