473,320 Members | 2,052 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,320 software developers and data experts.

Simple Python REGEX Question

I need to get the content inside the bracket.

eg. some characters before bracket (3.12345).

I need to get whatever inside the (), in this case 3.12345.

How do you do this with python regular expression?

May 11 '07 #1
4 1580
johnny wrote:
I need to get the content inside the bracket.

eg. some characters before bracket (3.12345).

I need to get whatever inside the (), in this case 3.12345.

How do you do this with python regular expression?
>>import re
x = re.search("[0-9.]+", "(3.12345)")
print x.group(0)
3.12345

There's a lot more to the re module, of course. I'd suggest reading the
manual, but this should get you started.
Gary Herron

May 11 '07 #2
On May 12, 2:21 am, Gary Herron <gher...@islandtraining.comwrote:
johnny wrote:
I need to get the content inside the bracket.
eg. some characters before bracket (3.12345).
I need to get whatever inside the (), in this case 3.12345.
How do you do this with python regular expression?
>import re
x = re.search("[0-9.]+", "(3.12345)")
print x.group(0)

3.12345

There's a lot more to the re module, of course. I'd suggest reading the
manual, but this should get you started.
>>s = "some chars like 987 before the bracket (3.12345) etc"
x = re.search("[0-9.]+", s)
x.group(0)
'987'

OP sez: "I need to get the content inside the bracket"
OP sez: "I need to get whatever inside the ()"

My interpretation:
>>for s in ['foo(123)bar', 'foo(123))bar', 'foo()bar', 'foobar']:
.... x = re.search(r"\([^)]*\)", s)
.... print repr(x and x.group(0)[1:-1])
....
'123'
'123'
''
None


May 12 '07 #3
On Fri, 11 May 2007 08:54:31 -0700, johnny wrote:
I need to get the content inside the bracket.

eg. some characters before bracket (3.12345).

I need to get whatever inside the (), in this case 3.12345.

How do you do this with python regular expression?
Why would you bother? If you know your string is a bracketed expression,
all you need is:

s = "(3.12345)"
contents = s[1:-1] # ignore the first and last characters

If your string is more complex:

s = "lots of things here (3.12345) and some more things here"

then the task is harder. In general, you can't use regular expressions for
that, you need a proper parser, because brackets can be nested.

But if you don't care about nested brackets, then something like this is
easy:

def get_bracket(s):
p, q = s.find('('), s.find(')')
if p == -1 or q == -1: raise ValueError("Missing bracket")
if p q: raise ValueError("Close bracket before open bracket")
return s[p+1:q-1]

Or as a one liner with no error checking:

s[s.find('(')+1:s.find(')'-1]
--
Steven.

May 12 '07 #4
johnny <ra*******@gmail.comwrote:
I need to get the content inside the bracket.
eg. some characters before bracket (3.12345).
I need to get whatever inside the (), in this case 3.12345.
How do you do this with python regular expression?
I'm going to presume that you mean something like:

I want to extract floating point numerics from parentheses
embedded in other, arbitrary, text.

Something like:
>>given='adfasdfafd(3.14159265)asdfasdfadsfasf'
import re
mymatch = re.search(r'\(([0-9.]+)\)', given).groups()[0]
mymatch
'3.14159265'
>>>
Of course, as with any time you're contemplating the use of regular
expressions, there are lots of questions to consider about the exact
requirements here. What if there are more than such pattern? Do you
only want the first match per line (or other string)? (That's all my
example will give you). What if there are no matches? My example
will raise an AttributeError (since the re.search will return the
"None" object rather than a match object; and naturally the None
object has no ".groups()' method.

The following might work better:
>>mymatches = re.findall(r'\(([0-9.]+)\)', given).groups()[0]
if len(mymatches):
...
... and, of couse, you might be better with a compiled regexp if
you're going to repeast the search on many strings:

num_extractor = re.compile(r'\(([0-9.]+)\)')
for line in myfile:
for num in num_extractor(line):
pass
# do whatever with all these numbers
--
Jim Dennis,
Starshine: Signed, Sealed, Delivered

May 12 '07 #5

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

Similar topics

6
by: Tony C | last post by:
I'm writing a python program which uses regular expressions, but I'm totally new to regexps. I've got Kuchling's "Regexp HOWTO", "Mastering Regular Expresions" by Oreilly, and have access to...
17
by: Michael McGarry | last post by:
Hi, I am just starting to use Python. Does Python have all the regular expression features of Perl? Is Python missing any features available in Perl? Thanks, Michael
75
by: Xah Lee | last post by:
http://python.org/doc/2.4.1/lib/module-re.html http://python.org/doc/2.4.1/lib/node114.html --------- QUOTE The module defines several functions, constants, and an exception. Some of the...
5
by: Vamsee Krishna Gomatam | last post by:
Hello, I'm having some problems understanding Regexps in Python. I want to replace "<google>PHRASE</google>" with "<a href=http://www.google.com/search?q=PHRASE>PHRASE</a>" in a block of text....
3
by: Vibha Tripathi | last post by:
Hi Folks, I put a Regular Expression question on this list a couple days ago. I would like to rephrase my question as below: In the Python re.sub(regex, replacement, subject)...
3
by: gisleyt | last post by:
I'm trying to compile a perfectly valid regex, but get the error message: r = re.compile(r'(*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') Traceback (most recent call last): File...
8
by: Xah Lee | last post by:
the Python regex documentation is available at: http://xahlee.org/perl-python/python_re-write/lib/module-re.html Note that, i've just made the terms of use clear. Also, can anyone answer what...
0
by: Neil Cerutti | last post by:
I'm a royal n00b to writing translators, but you have to start someplace. In my Python project, I've decided that writing the dispatch code to sit between the Glulx virtual machine and the Glk...
13
by: James | last post by:
Hello, I'm a newbie to Python & wondering someone can help me with this... I have this code: -------------------------- #! /usr/bin/python import sys
10
by: Raymond | last post by:
For some reason I'm unable to grok Python's string.replace() function. Just trying to parse a simple IP address, wrapped in square brackets, from Postfix logs. In sed this is straightforward given:...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.