Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104191

Re: Regex: Perl to Python

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: Regex: Perl to Python
Date 2016-03-07 08:48 +0100
Organization None
Message-ID <mailman.8.1457336938.10335.python-list@python.org> (permalink)
References <nbj0k0$12gk$1@gioia.aioe.org>

Show all headers | View raw


Fillmore wrote:

> 
> Hi, I'm trying to move away from Perl and go to Python.
> Regex seems to bethe hardest challenge so far.
> 
> Perl:
> 
> while (<HEADERFILE>) {
>      if (/(\d+)\t(.+)$/) {
> print $1." - ". $2."\n";
>      }
> }
> 
> into python
> 
> pattern = re.compile(r"(\d+)\t(.+)$")
> with open(fields_Indexfile,mode="rt",encoding='utf-8') as headerfile:
>      for line in headerfile:
>          #sys.stdout.write(line)
>          m = pattern.match(line)
>          print(m.group(0))
>      headerfile.close()
> 
> but I must be getting something fundamentally wrong because:
> 
> Traceback (most recent call last):
>    File "./slicer.py", line 30, in <module>
>      print(m.group(0))
> AttributeError: 'NoneType' object has no attribute 'group'
> 
> 
>   why is 'm' a None?

match() matches from the begin of the string, use search():

match = pattern.search(line)
if match is not None:
    print(match.group(1), "-", match.group(2))

Also, in Python you often can use string methods instead of regular 
expressions:

index, tab, value = line.strip().partition("\t")
if tab and index.isdigit():
    print(index, "-", value)

> the input data has this format:
> 
>           :
>       3	prop1
>       4	prop2
>       5	prop3
> 

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Regex: Perl to Python Fillmore <fillmore_remove@hotmail.com> - 2016-03-06 23:38 -0500
  Re: Regex: Perl to Python Chris Angelico <rosuav@gmail.com> - 2016-03-07 15:45 +1100
  Re: Regex: Perl to Python Terry Reedy <tjreedy@udel.edu> - 2016-03-06 23:48 -0500
    Re: Regex: Perl to Python Rustom Mody <rustompmody@gmail.com> - 2016-03-06 21:53 -0800
    Re: Regex: Perl to Python Rustom Mody <rustompmody@gmail.com> - 2016-03-06 21:53 -0800
  Re: Regex: Perl to Python Peter Otten <__peter__@web.de> - 2016-03-07 08:48 +0100
  Re: Regex: Perl to Python Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 07:50 -0500

csiph-web