Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Shell pattern to regular expression code

Reply
Thread Tools

Shell pattern to regular expression code

 
 
Stephen Kennedy
Guest
Posts: n/a
 
      08-06-2003

Hi all, I was searched on the web for code to handle {} as in *.{foo,bar}
(fnmatch does not handle this case) and surprisingly didn't find any.
So I wrote some. Here it is:

Stephen

#! /usr/bin/env python

import re

def translate(pat):
"""Translate a shell PATTERN to a regular expression.

There is no way to quote meta-characters.
"""

i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i+1
if c == '*':
res += '.*'
elif c == '?':
res += '.'
elif c == '[':
try:
j = pat.index(']', i)
stuff = pat[i:j]
i = j+1
if stuff[0] == '!':
stuff = '^%s' % stuff[1:]
elif stuff[0] == '^':
stuff = r'\^%s' % stuff[1:]
res += '[%s]' % stuff
except ValueError:
res += r'\['
elif c == '{':
try:
j = pat.index('}', i)
stuff = pat[i:j]
i = j+1
res += '(%s)' % "|".join([translate(p)[:-1] for p in stuff.split(",")])
except ValueError:
res += r'\{'
else:
res += re.escape(c)
return res + "$"

lof = open("sourcelist").readlines()
pats = ["*.*", "*.[ac]", "*.[ac]*", "*.[!ac]*", "*.[ac]x*", "*.{gif,jpg}", "*.{a*,y*}"]
for pat in pats[-1:]:
print "***", pat, "***", translate(pat)
regex = re.compile( translate(pat) )
print "\n".join( [f.strip() for f in lof if regex.match(f)!=None][:20] )

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Regular Expression pattern group JH Python 1 06-15-2006 07:13 AM
Regular Expression for pattern substitution Vibha Tripathi Python 3 07-01-2005 06:31 PM
Regular expression does not work in pattern facet? Johann Sijpkes XML 2 07-14-2004 05:30 PM
Dynamically changing the regular expression of Regular Expression validator VSK ASP .Net 2 08-24-2003 02:47 PM
Serialization of a regular expression pattern MARTIN Herve Java 1 07-22-2003 09:31 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57