How do I regex match everything that is between two strings? The things between two strings span several lines and can contain all html characters too.
For example:
<p>something</p>
<!-- OPTIONAL -->
<p class="sdf"> some text</p>
<p> some other text</p>
<!-- OPTIONAL END -->
<p>The end</p>
I want to strip the whole optional part off. but the greedy any character match isn't doing what I wanted.. the pattern I'm using is
<!-- OPTIONAL -->.*<!-- OPTIONAL END -->
<!-- OPTIONAL -->(.*)<!-- OPTIONAL END -->
<!-- OPTIONAL -->(.*)\s+<!-- OPTIONAL END -->
(?=<!-- OPTIONAL -->)(.*)\s+<!-- OPTIONAL END -->
All of them match the first optional tag, if only the first part is given, but doesn't do well with complete lines.
Here's an example: http://regexr.com?352bk
Thanks
The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.
Multiline option, it matches either the newline character ( \n ) or the end of the input string. It does not, however, match the carriage return/line feed character combination.
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. You cannot change this property directly.
The fullmatch() function returns a Match object if the whole string matches the search pattern of a regular expression, or None otherwise. The syntax of the fullmatch() function is as follows: re.fullmatch(pattern, string, flags=0)
playing with your example I think I found the answer, check this in your code:
<!-- OPTIONAL -->[\w\W]*<!-- OPTIONAL END -->
I'll hope this help
Check the dotall checkbox in RegExr :)
Without the dotall flag (the s
in /regex/s
), a dot (.
) won't match carriage returns.
You should use .*?
instead of .*
to lazy match the optional content (see the PLEASE DO NOT MATCH!
sentence in the examples).
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