473,769 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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='12a b'"
"parameter='12a b' biz boz"
"parameter="12a b""
"parameter="12a b" 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'pa rameter=(["\']?(.*?)\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 1630
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='12a b'"
"parameter='12a b' biz boz"
"parameter="12a b""
"parameter="12a b" 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'pa rameter=(["\']?(.*?)\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='12a b'"
"parameter='12a b' biz boz"
"parameter="12a b""
"parameter="12a b" 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'pa rameter=(["\']?(.*?)\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)...thou gh 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=12a b', True),
('parameter=12a b foo bar', True),
("parameter='12 ab'", True),
("parameter='12 ab' biz boz", True),
('parameter="12 ab"', True),
('parameter="12 ab" junk', True),
('parameter="12 ab', False),
('parameter=\'1 2ab', False),
('parameter="12 ab\'', False),
('parameter="12 ab\' foo baz', False)
]
exp = r'parameter=((["\'])(.*?)\2|[^\'" ]+).*'
r = re.compile(exp)
print "Using regexp: %s" % exp
for test,expectedRe sult 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='12a b'"
"parameter='12a b' biz boz"
"parameter="12a b""
"parameter="12a b" junk"

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

'12ab'

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

"parameter=12 ab"
"parameter=12 ab foo bar"
"parameter='1 2ab'"
"parameter='1 2ab' biz boz"
"parameter="1 2ab""
"parameter="1 2ab" 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
4182
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 regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the...
4
5186
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 adate LIKE "2004.01.10 __:15") .... into something like this: .... where adate LIKE "2004.01.10 __:(30/15)" ...
7
3830
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 want to avoid that. My question here is if there is a way to pass either a memory stream or array of "find", "replace" expressions or any other way to avoid multiple copies of a string. Any help will be highly appreciated
25
5166
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 (CONDUCTION DEFECT) 37.33/2 HEART (CONDUCTION DEFECT) WITH CATHETER 37.34/2 " the expression is "HEART (CONDUCTION DEFECT)". How do I gain access to the expression (not the matches) at runtime? Thanks, Mike
2
2015
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
2862
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 enclosed in single quotes to also be valid, no matter where they appear. I tried the following: <xs:pattern value="^*('*)*" />
1
4386
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 the first regular expression that matches the string. I've gor the regular expressions ordered so that the highest priority is first (if two or more regular expressions match the string I want the first one returned) The code that does this has...
4
1742
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 enter "a" or "e" in the box and bring back everyone with an "a" or "e" in their name. I figure that a regular expression validation is the way to go, and I tried this: ValidationExpression="^({3,255})$"
8
1758
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 function that creates a connection object and executes an SQL query, i.e. function Query(). I always sanitize my SQL statements to buffer all apostrophes with two apostrophes ala function Buffer(). However, I have long wondered if I could do away with...
10
1688
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. query = ' " some words" with and "without quotes " ' p = re.compile(magic_regular_expression) $ <--- the magic happens m = p.match(query)
0
9586
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9861
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8869
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.