Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I express a multi-line regex in assertRegex in Python 3?

I'm using the assertRegex() function from the unittest library in Python 3.4. It only takes two relevant parameters: the text to match against and the regex. The seems to prevent me from expressing any regex-related constants such as re.MULTILINE.

How can I construct or specify a multi-line regex and use it with assertRegex()? Alternatively, is there a related way of solving my problem?

like image 800
Andrew Ferrier Avatar asked Apr 17 '15 14:04

Andrew Ferrier


2 Answers

See here in the Python docs:

(?iLmsux)

(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.

Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

like image 111
Malik Brahimi Avatar answered Sep 19 '22 01:09

Malik Brahimi


One way is to construct Regexp with re.compile (Official Python 3 reference). An example is

self.assertRegex(str1, re.compile('\\bcd '+re.escape(os.getcwd())+'\n', re.M | re.I))

This is useful when the expression is complex.

like image 37
Masa Sakano Avatar answered Sep 18 '22 01:09

Masa Sakano