473,408 Members | 1,738 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,408 software developers and data experts.

Regular expression query

It's probably quite simple, but what I want is a regular expression to
parse strings of the form:

"parameter=12ab"
"parameter=12ab foo bar"
"parameter='12ab'"
"parameter='12ab' biz boz"
"parameter="12ab""
"parameter="12ab" junk"

in each case returning 12ab as a match. "parameter" is known and fixed.
The parameter value may or may not be enclosed in single or double
quotes, and may or may not be the last thing on the line. If the value
is quoted, it may contain spaces.

I've tried a regex of the form:
re.compile(r'parameter=(["\']?(.*?)\1( *|$)')

This works fine when the parameter's value is quoted, but if the quotes
are missing, it falls over since the \1 is empty and so the non-greedy
"match anything" ends up matching nothing.

Any suggestions?

Thanks

<M>

Feb 3 '06 #1
4 1606
Martin Biddiscombe wrote:
It's probably quite simple, but what I want is a regular expression
If it's simple, then you probably *dont* want a regexp.
to
parse strings of the form:

"parameter=12ab"
"parameter=12ab foo bar"
"parameter='12ab'"
"parameter='12ab' biz boz"
"parameter="12ab""
"parameter="12ab" junk"

in each case returning 12ab as a match. "parameter" is known and fixed.
The parameter value may or may not be enclosed in single or double
quotes, and may or may not be the last thing on the line. If the value
is quoted, it may contain spaces.

I've tried a regex of the form:
re.compile(r'parameter=(["\']?(.*?)\1( *|$)')

This works fine when the parameter's value is quoted, but if the quotes
are missing, it falls over since the \1 is empty and so the non-greedy
"match anything" ends up matching nothing.

Any suggestions?
yes : forget regexps, use str methods.

parse = lambda l: \ l.split('=',1)[1].split()[0].strip().strip("'\"")

NB : I tried my best to make it as obfuscated as a regexp so you still
gain extra bonus points from Perl-addicts !-p - but feel free to rewrite
this cleanly.

Thanks


HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 3 '06 #2
> "parameter=12ab"
"parameter=12ab foo bar"
"parameter='12ab'"
"parameter='12ab' biz boz"
"parameter="12ab""
"parameter="12ab" junk"

in each case returning 12ab as a match. "parameter" is known and fixed.
The parameter value may or may not be enclosed in single or double
quotes, and may or may not be the last thing on the line. If the value
is quoted, it may contain spaces.

I've tried a regex of the form:
re.compile(r'parameter=(["\']?(.*?)\1( *|$)')


Below is a test-harness that seemed to spit out the results you
want (I threw in some bogus tests to make sure they failed too)
with the given value for "exp".

The resulting match object will have your desired value in
group(1)...though it will include whatever quotes happened to be
in it. You may also need to anchor accordingly with "^" and "$"

It doesn't gracefully handle escaped quotes in your value

-tim
import re
tests = [
('parameter=12ab', True),
('parameter=12ab foo bar', True),
("parameter='12ab'", True),
("parameter='12ab' biz boz", True),
('parameter="12ab"', True),
('parameter="12ab" junk', True),
('parameter="12ab', False),
('parameter=\'12ab', False),
('parameter="12ab\'', False),
('parameter="12ab\' foo baz', False)
]
exp = r'parameter=((["\'])(.*?)\2|[^\'" ]+).*'
r = re.compile(exp)
print "Using regexp: %s" % exp
for test,expectedResult in tests:
if r.match(test):
result = True
else:
result = False
if result == expectedResult:
print "[%s] passed" % test
else:
print "[%s] failed (expected %s, got %s)" % (test,
expectedResult, result)

Feb 3 '06 #3
Martin Biddiscombe wrote:
"parameter=12ab"
"parameter=12ab foo bar"
"parameter='12ab'"
"parameter='12ab' biz boz"
"parameter="12ab""
"parameter="12ab" junk"

import shlex
def extract(s): .... s = s.split("=")[1]
.... s = shlex.split(s)[0]
.... return s
.... extract("parameter=12ab") '12ab' extract("parameter=12ab foo bar") '12ab' extract("parameter='12ab'") '12ab' extract("parameter='12ab' biz boz") '12ab' extract('parameter="12ab"') '12ab' extract('parameter="12ab" junk')

'12ab'

--
Giovanni Bajo
Feb 4 '06 #4
Giovanni Bajo wrote:
Martin Biddiscombe wrote:

"parameter=12ab"
"parameter=12ab foo bar"
"parameter='12ab'"
"parameter='12ab' biz boz"
"parameter="12ab""
"parameter="12ab" junk"


import shlex
def extract(s):


... s = s.split("=")[1]
... s = shlex.split(s)[0]
... return s


I definitevely have to learn and use the shlex module.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 6 '06 #5

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

Similar topics

1
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make...
4
by: Együd Csaba | last post by:
Hi All, I'd like to "compress" the following two filter expressions into one - assuming that it makes sense regarding query execution performance. .... where (adate LIKE "2004.01.10 __:30" or...
7
by: Billa | last post by:
Hi, I am replaceing a big string using different regular expressions (see some example at the end of the message). The problem is whenever I apply a "replace" it makes a new copy of string and I...
25
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART...
2
by: comp.lang.php | last post by:
I am trying to replace within the HTML string $html the following: With Where I'm replacing "action=move_image" with "action=<?= $_REQUEST ?>"
6
by: rorymo | last post by:
I have a regular expression that allows only certain characters to be valid in an xml doc as follows: <xs:pattern value="^*" /> What I want to do is also allow any unicode character that is...
1
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find...
4
by: Brian Simmons | last post by:
Hi All, I've got a textbox where I want to make sure the person has entered at least 3 characters before submitting (it's like a partial name lookup type of query), so I don't want them to just...
8
by: Nicodemas | last post by:
Hello all, could not find a regular expression forum, so I thought I would post it to my favorite of the forums. I have a series of applications I've developed which all use a centralized...
10
by: Julien | last post by:
Hi, I'm fairly new in Python and I haven't used the regular expressions enough to be able to achieve what I want. I'd like to select terms in a string, so I can then do a search in my database....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.