473,835 Members | 1,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1607
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...@island training.comwro te:
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("Mis sing bracket")
if p q: raise ValueError("Clo se 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*******@gmai l.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='adfasd fafd(3.14159265 )asdfasdfadsfas f'
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(l ine):
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
2054
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 online stuff too. But I would like to find a mailing list or newsgroup where I can ask questions about regexps (when things don't work), not specifically dealing with Python. When I have Python-regexp questions, I'll post them here of course.
17
3119
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
4677
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 functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form UNQUOTE
5
2911
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. How can I achieve this in Python? Sorry for the naive question but the documentation is really bad :-( Regards, GVK
3
9749
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) method/function, I need the second argument 'replacement' to be another regular expression ( not a string) . So when I find a 'certain kind of string' in
3
5274
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 "<stdin>", line 1, in ? File "/usr/lib/python2.3/sre.py", line 179, in compile return _compile(pattern, flags) File "/usr/lib/python2.3/sre.py", line 230, in _compile
8
2246
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 is the precise terms of license of the official python documentation? The official python.org doc site is not clear. Note also, that the regex syntax used by Perl is the same as Python.
0
1227
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 API will be best done automatically, using the handy prototypes. Below is the prototype of the lexer, and I'd like some comments in case I'm doing something silly already.
13
6224
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
3575
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: line = "date process text more text" sed -e 's/^.*\.*$//' yet the following Python code does nothing:
0
9652
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
10812
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...
1
10561
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9346
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...
0
6966
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();...
0
5804
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4434
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3995
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3089
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.