Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python RegExp global flag

Is there a flag or some special key in python to use pattern multiple times. I used to test http://gskinner.com/RegExr/ my RegExp, it worked correctly in it. But when testing in correct enviorment match only returns None.

import re pattern = r"(?P<date>--\d\d-\w+:\d\d)[ \t]+(?P<user>\w+)[ \t]+(?P<method>[\w ]+)[\" ]*    (?P<file>[\w\\:\.]+)@@(?P<version>[\w\\]+)[\" ]*(?P<labels>[\(\w, \.\)]+){0,1}[\s \"]*(?P<comment>[\w \.-]+){0,1}[\"]" base = """ --02-21T11:22  user3   create version "W:\foo\bar\fooz.bat@@\main\1" (label1, label2,   label3, label22, label33, ...)  "merge in new bat-based fooz installer"  --02-21T11:22  user1   create version "W:\foo\bar\fooz.bat@@\main\0"  --02-21T11:22  user2   create branch "W:\foo\bar\fooz.bat@@\main\"  "merge in new bat-based fooz installer"  --02-13T11:22  user1   create version     "W:\foo\bar\fooz.bat@@\main\1"    "Made to use new fooz.bat"  """ r = re.match(pattern, base) print(r) 
like image 340
Metsavaht Avatar asked Jul 27 '12 11:07

Metsavaht


People also ask

What does the global flag in regex do?

The " g " flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global (" g ") and sticky (" y ") will ignore the global flag and perform sticky matches.

What will the regular expression match?

By default, regular expressions will match any part of a string. It's often useful to anchor the regular expression so that it matches from the start or end of the string: ^ matches the start of string. $ matches the end of the string.

What is regular expression in Python?

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.


2 Answers

re.match tries to match the pattern at the start of the string. You are looking for re.search, re.findall or re.finditer

like image 120
Mariy Avatar answered Sep 19 '22 20:09

Mariy


Each of the Python regular expression matching functions are useful for different purposes.

re.match always starts at the beginning of the string.

re.search steps through the string from the start looking for the first match. It stops when it finds a match.

re.findall returns a list of all the search matches.

In all the cases above, if there's a group in the regex pattern, then the item you get back is a tuple of the full match followed by each group match in the order they appear in the regex pattern.

like image 43
Mars Landis Avatar answered Sep 18 '22 20:09

Mars Landis