Do Python modes support something like Perl \ G?

I have a Perl regex (shown here , although understanding all of this, hopefully not necessarily to answer this question), which contains the \ G metacharacter. I would like to translate it to Python, but Python does not seem to support \ G. What can I do?

+5
source share
5 answers

Try the following:

import re
re.sub()
re.findall()
re.finditer()

eg:

# Finds all words of length 3 or 4
s = "the quick brown fox jumped over the lazy dogs."
print re.findall(r'\b\w{3,4}\b', s)

# prints ['the','fox','over','the','lazy','dogs']
+4
source

You can use re.matchto match bound patterns. re.matchwill only match at the beginning (position 0) of the text or where you specify.

def match_sequence(pattern,text,pos=0):
  pat = re.compile(pattern)
  match = pat.match(text,pos)
  while match:
    yield match
    if match.end() == pos:
      break # infinite loop otherwise
    pos = match.end()
    match = pat.match(text,pos)

, 0 .

>>> for match in match_sequence(r'[^\W\d]+|\d+',"he11o world!"):
...   print match.group()
...
he
11
o
+2

, , \G:

import re

def replace(match):
    if match.group(0)[0] == '/': return match.group(0)
    else: return '<' + match.group(0) + '>'

source = '''http://a.com http://b.com
//http://etc.'''

pattern = re.compile(r'(?m)^//.*$|http://\S+')
result = re.sub(pattern, replace, source)
print(result)

( Ideone):

<http://a.com> <http://b.com>
//http://etc.

, , : URL . (, , ..), , , .

, , \G. Java, .

( Python, , .)

+2

Python /g regexen \G regex. .

+1

Do not try to put everything in one expression, as it becomes very difficult to read, translate (as you yourself see) and support.

import re
lines = [re.sub(r'http://[^\s]+', r'<\g<0>>', line) for line in text_block.splitlines() if not line.startedwith('//')]
print '\n'.join(lines)

Python is usually not the best when you literally translate from Perl, it has its own programming patterns.

0
source

All Articles