Shell pattern to regular expression code

Discussion in 'Python' started by Stephen Kennedy, Aug 6, 2003.

  1. 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+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] )
     
    Stephen Kennedy, Aug 6, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. VSK
    Replies:
    2
    Views:
    2,394
  2. MARTIN Herve
    Replies:
    1
    Views:
    516
    Roedy Green
    Jul 22, 2003
  3. Johann Sijpkes
    Replies:
    2
    Views:
    476
    Johann Sijpkes
    Jul 14, 2004
  4. Vibha Tripathi

    Regular Expression for pattern substitution

    Vibha Tripathi, Jul 1, 2005, in forum: Python
    Replies:
    3
    Views:
    325
    Devan L
    Jul 1, 2005
  5. JH
    Replies:
    1
    Views:
    303
Loading...

Share This Page