473,671 Members | 2,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

regular expression: perl ==> python

Hi,
i am so use to perl's regular expression that i find it hard
to memorize the functions in python; so i would appreciate if
people can tell me some equivalents.

1) In perl:
$line = "The food is under the bar in the barn.";
if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }

in python, I don't know how I can do this?
How does one capture the $1? (I know it is \1 but it is still not clear
how I can simply print it.
thanks

Jul 18 '05 #1
17 1988
le*******@yahoo .com wrote:

1) In perl:
$line = "The food is under the bar in the barn.";
if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }

in python, I don't know how I can do this?


I don't know Perl very well, but I believe this is more or less the
equivalent:
import re
line = "The food is under the bar in the barn."
matcher = re.compile(r'fo o(.*)bar')
match = matcher.search( line)
print 'got <%s>' % match.group(1) got <d is under the bar in the >

Of course, you can do this in fewer lines if you like:
print 'got <%s>' % re.search(r'foo (.*bar)', line).group(1)

got <d is under the bar in the bar>

Steve
Jul 18 '05 #2
<le*******@yaho o.com> wrote:
i am so use to perl's regular expression that i find it hard
to memorize the functions in python; so i would appreciate if
people can tell me some equivalents.

1) In perl:
$line = "The food is under the bar in the barn.";
if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }

in python, I don't know how I can do this?
How does one capture the $1? (I know it is \1 but it is still not clear
how I can simply print it.


in Python, the RE machinery returns match objects, which has methods
that let you dig out more information about the match. "captured groups"
are available via the "group" method:

m = re.search(..., line)
if m:
print "got", m.group(1)

see the regex howto (or the RE chapter in the library reference) for more
information:

http://www.amk.ca/python/howto/regex/

</F>

Jul 18 '05 #3
JZ
Dnia 21 Dec 2004 21:12:09 -0800, le*******@yahoo .com napisa³(a):
1) In perl:
$line = "The food is under the bar in the barn.";
if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }

in python, I don't know how I can do this?
How does one capture the $1? (I know it is \1 but it is still not clear
how I can simply print it.
thanks


import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)

--
JZ ICQ:6712522
http://zabiello.om
Jul 18 '05 #4
"JZ" <wn******@mnovr yyb.pbz> wrote:
import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)


Traceback (most recent call last):
File "jz.py", line 4, in ?
print 'got %s\n' % _.group(1)
NameError: name '_' is not defined

</F>

Jul 18 '05 #5
Fredrik Lundh wrote:
"JZ" <wn******@mnovr yyb.pbz> wrote:

import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)

Traceback (most recent call last):
File "jz.py", line 4, in ?
print 'got %s\n' % _.group(1)
NameError: name '_' is not defined


He was using the python interactive prompt, which I suspect you already
knew.
Jul 18 '05 #6
JZ
Dnia Wed, 22 Dec 2004 10:27:39 +0100, Fredrik Lundh napisa³(a):
import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)


Traceback (most recent call last):
File "jz.py", line 4, in ?
print 'got %s\n' % _.group(1)
NameError: name '_' is not defined


I forgot to add: I am using Python 2.3.4/Win32 (from ActiveState.com ). The
code works in my interpreter.

--
JZ
Jul 18 '05 #7
"JZ" wrote:
import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)


Traceback (most recent call last):
File "jz.py", line 4, in ?
print 'got %s\n' % _.group(1)
NameError: name '_' is not defined


I forgot to add: I am using Python 2.3.4/Win32 (from ActiveState.com ). The
code works in my interpreter.


only if you type it into the interactive prompt. see:

http://www.python.org/doc/2.4/tut/no...00000000000000

"In interactive mode, the last printed expression is assigned to the variable _.
This means that when you are using Python as a desk calculator, it is some-
what easier to continue calculations /.../"

the "_" symbol has no special meaning when you run a Python program, so the
"if re.search" construct won't work.

</F>

Jul 18 '05 #8
JZ
Dnia Wed, 22 Dec 2004 16:55:55 +0100, Fredrik Lundh napisa³(a):
the "_" symbol has no special meaning when you run a Python program,


That's right. So the final code will be:

import re
line = "The food is under the bar in the barn."
found = re.search('foo( .*)bar',line)
if found: print 'got %s\n' % found.group(1)

--
JZ ICQ:6712522
http://zabiello.com
Jul 18 '05 #9
> 1) In perl:
$line = "The food is under the bar in the barn.";
if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }

in python, I don't know how I can do this?
How does one capture the $1? (I know it is \1 but it is still not clear
how I can simply print it.
thanks

Fredrik Lundh <fr*****@python ware.com> wrote: "JZ" <wn******@mnovr yyb.pbz> wrote:
import re
line = "The food is under the bar in the barn."
if re.search(r'foo (.*)bar',line):
print 'got %s\n' % _.group(1)


Traceback (most recent call last):
File "jz.py", line 4, in ?
print 'got %s\n' % _.group(1)
NameError: name '_' is not defined


I've found that a slight irritation in python compared to perl - the
fact that you need to create a match object (rather than relying on
the silver thread of $_ (etc) running through your program ;-)

import re
line = "The food is under the bar in the barn."
m = re.search(r'foo (.*)bar',line)
if m:
print 'got %s\n' % m.group(1)

This becomes particularly irritating when using if, elif etc, to
match a series of regexps, eg

line = "123123"
m = re.search(r'^(\ d+)$', line)
if m:
print "int",int(m.gro up(1))
else:
m = re.search(r'^(\ d*\.\d*)$', line)
if m:
print "float",float(m .group(1))
else:
print "unknown thing", line

The indentation keeps growing which looks rather untidy compared to
the perl

$line = "123123";
if ($line =~ /^(\d+)$/) {
print "int $1\n";
}
elsif ($line =~ /^(\d*\.\d*)$/) {
print "float $1\n";
}
else {
print "unknown thing $line\n";
}

Is there an easy way round this? AFAIK you can't assign a variable in
a compound statement, so you can't use elif at all here and hence the
problem?

I suppose you could use a monstrosity like this, which relies on the
fact that list.append() returns None...

line = "123123"
m = []
if m.append(re.sea rch(r'^(\d+)$', line)) or m[-1]:
print "int",int(m[-1].group(1))
elif m.append(re.sea rch(r'^(\d*\.\d *)$', line)) or m[-1]:
print "float",flo at(m[-1].group(1))
else:
print "unknown thing", line

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Jul 18 '05 #10

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

Similar topics

4
2205
by: pekka niiranen | last post by:
Hi there, I have perl script that uses dynamically constructed regular in this way: ------perl code starts ---- $result ""; $key = AAA\?01; $key = quotemeta $key; $line = " s^\?AAA\?01^BBB^g; #Comment "
3
9733
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
19
2303
by: Davy | last post by:
Hi all, I am a C/C++/Perl user and want to switch to Python (I found Python is more similar to C). Does Python support robust regular expression like Perl? And Python and Perl's File content manipulation, which is better? Any suggestions will be appreciated!
5
2311
by: Avi Kak | last post by:
Folks, Does regular expression processing in Python allow for executable code to be embedded inside a regular expression? For example, in Perl the following two statements $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw mello\n"})/; "jellohellomello" =~ /$regex/;
34
1833
by: Antoine De Groote | last post by:
Hello, Can anybody tell me the reason(s) why regular expressions are not built into Python like it is the case with Ruby and I believe Perl? Like for example in the following Ruby code line = 'some string' case line when /title=(.*)/
1
2828
by: Wehrdamned | last post by:
Hi, As I understand it, python uses a pcre engine to work with regular expression. My question is, then, why expressions like : Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.4/sre.py", line 180, in compile return _compile(pattern, flags)
3
1537
by: John Nagle | last post by:
Here's a large Perl regular expression, from a Perl address parser in CPAN: use re 'eval'; $Addr_Match{street} = qr/ (?: # special case for addresses like 100 South Street (?:($Addr_Match{direct})\W+ (?{ $_{street} = $^N }) ($Addr_Match{type})\b (?{ $_{type} = $^N })) | (?:($Addr_Match{direct})\W+ (?{ $_{prefix} = $^N }))?
3
2795
by: seberino | last post by:
How similar is Python's re module (regular expressions) compared to Perl's and grep's regular expression syntaxes? I really hope regular expression syntax is sufficiently standardized that we don't have to learn new dialects everytime we move from one language or shell command to another. chris
8
3111
by: Uwe Schmitt | last post by:
Hi, Is anobody aware of this post: http://swtch.com/~rsc/regexp/regexp1.html ? Are there any plans to speed up Pythons regular expression module ? Or is the example in this artricle too far from reality ??? Greetings, Uwe
0
8483
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
8402
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
8927
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
8825
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8605
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
8676
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
5703
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
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2819
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

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.