473,398 Members | 2,368 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Shell pattern to regular expression code


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] )

Jul 18 '05 #1
0 1365

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: speedster | last post by:
Hi. I need some help converting some php to perl. $meminfo = shell_exec( "free -o" ); I need to execute "free-o" in shell and get the results. It grabs memory information about a linux...
2
by: Johann Sijpkes | last post by:
Hi, Just before going mad I thought asking this newsgroup would be a good idea. I want to validate dates using a schema but somehow the regexp is not performed by the validator? (at w3c..). I...
1
by: Jeff | last post by:
For the life of me, I can't create a working regular expression for a schema pattern to do the following: Validates if an entire word does NOT match the entire word in the pattern. For...
5
by: Abby Lee | last post by:
I ask the user to enter a time in the formatio 12:30 PM. onChange I send the string to this function. I'm using alert boxes to test it...and am always getting the "Does not work" alert box. What am...
4
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a...
11
by: Dimitris Georgakopuolos | last post by:
Hello, I have a text file that I load up to a string. The text includes certain expression like {firstName} or {userName} that I want to match and then replace with a new expression. However,...
0
by: WALDO | last post by:
Assuming the following code: Dim strPattern As String = "(\d{3})(-)(\d{4})" Dim strMatch As String = "555-1234" Dim regExp As New RegEx(strPattern) Dim matches As MatchCollection =...
3
by: Hari | last post by:
Hi all, I need to get a part of string which follows a pattern 'addr=' For example: a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype nfs(rw,addr=192.168.1.17)"
2
by: =?Utf-8?B?QWFyb24=?= | last post by:
Hi, I'm having a tricky problem where I want to accept a regular expression pattern from user input but can't get teh escape characters to be prcoessed correctly. If I take the same pattern and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.