Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex findall and multiline

Tags:

python

regex

python 2.6.8

s= '''
foo 
bar
baz
'''
>>>re.findall(r'^\S*',s,re.MULTILINE)
['', 'foo', 'bar', 'baz', '']
>>>ptrn = re.compile(r'^\S*',re.MULTILINE)
>>>ptrn.findall(s)
['', 'foo', 'bar', 'baz', '']
>>>ptrn.findall(s,re.MULTILINE)
['baz', '']

Why is there a difference between using MULTILINE flag in findall?

like image 603
kmad Avatar asked Aug 14 '12 18:08

kmad


People also ask

What is RegEx Findall?

findall. findall() is probably the single most powerful function in the re module. Above we used re.search() to find the first match for a pattern. findall() finds *all* the matches and returns them as a list of strings, with each string representing one match.

How do you match multiple lines in python?

MULTILINE flag tells python to make the '^' and '$' special characters match the start or end of any line within a string. Using this flag: >>> match = re.search(r'^It has. *', paragraph, re.

Which flag will search over multiple lines?

The m flag indicates that a multiline input string should be treated as multiple lines. For example, if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.

Which flag will search over multiple lines in python?

Practical Data Science using PythonDOTALL flag tells python to make the '. ' special character match all characters, including newline characters. This is a paragraph. It has multiple lines.


1 Answers

When calling the findall() method on a regex object, the second parameter is not the flags argument (because that has already been used when compiling the regex) but the pos argument, telling the regex engine at which point in the string to start matching.

re.MULTILINE is just an integer (that happens to be 8).

See the docs.

like image 63
Tim Pietzcker Avatar answered Oct 10 '22 15:10

Tim Pietzcker