The Python docs say:
re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...
So what's going on when I get the following unexpected result?
>>> import re >>> s = """// The quick brown fox. ... // Jumped over the lazy dog.""" >>> re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.'
By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.
Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. @Amber: I infer from your answer that unlike str. replace(), we can't use variables a) in raw strings; or b) as an argument to re. sub; or c) both.
The full definition of re.sub is: re.sub(pattern, repl, string[, count, flags]) Which means that if you tell Python what the parameters are, then you can pass flags without passing count : re.sub('^//', '', s, flags=re.MULTILINE) or, more concisely: re.sub('^//', '', s, flags=re.M)
If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.
Look at the definition of re.sub
:
re.sub(pattern, repl, string[, count, flags])
The 4th argument is the count, you are using re.MULTILINE
(which is 8) as the count, not as a flag.
Either use a named argument:
re.sub('^//', '', s, flags=re.MULTILINE)
Or compile the regex first:
re.sub(re.compile('^//', re.MULTILINE), '', s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With