Consider the following regular expressions:
/xyz^abc/
/xyz$abc/
What will these match?
I know that
^
), when used at the beginning of a regex, matches the beginning of lines$
) , when used at the end of a regex, matches the end of lines^
), when used as the first character of a character class, negates the classI believe the given regular expressions won't ever match anything, but I am not sure.
Depending on the options, a ^
or a $
in the middle of a regular expression can cause a match:
>>> if re.search(r'xyz.^abc', "xyz\nabc", re.MULTILINE | re.DOTALL):
... print "Matched"
...
Matched
MULTILINE
makes ^
match the start of a line, even if that line isn't at the start of the string. DOTALL
makes .
match newlines.
(I can't find a way to make your exact examples match anything.)
Those won't match anything. However:
/(xyz$|^xyz)/
That would match any line that begins OR ends with xyz.
Update:
Andy G points out that multi-line mode may find a match for your regex strings. But this only applies if the implementation is configured to support mid-string anchor matching.
This is from Regular-Expressions.info (my favorite place for learning & understanding regular expressions):
If you have a string consisting of multiple lines, like first line\nsecond line (where \n indicates a line break), it is often desirable to work with lines, rather than the entire string. Therefore, all the regex engines discussed in this tutorial have the option to expand the meaning of both anchors. ^ can then match at the start of the string (before the f in the above string), as well as after each line break (between \n and s). Likewise, $ will still match at the end of the string (after the last e), and also before every line break (between e and \n).
In text editors like EditPad Pro or GNU Emacs, and regex tools like PowerGREP, the caret and dollar always match at the start and end of each line. This makes sense because those applications are designed to work with entire files, rather than short strings.
In all programming languages and libraries discussed on this website , except Ruby, you have to explicitly activate this extended functionality. It is traditionally called "multi-line mode". In Perl, you do this by adding an m after the regex code, like this: m/^regex$/m;. In .NET, the anchors match before and after newlines when you specify RegexOptions.Multiline, such as in Regex.Match("string", "regex", RegexOptions.Multiline).
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