472,328 Members | 2,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,328 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 1536
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...
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...
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...
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...
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...
3
by: gisleyt | last post by:
I'm trying to compile a perfectly valid regex, but get the error message: r =...
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...
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...
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 ...
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...
0
by: tammygombez | last post by:
Hey fellow JavaFX developers, I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue....
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
1
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

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.