4 ms·
The potential trouble with $ (even in single-line mode) is that it matches the end of a string BOTH with AND without a newline at the end. If you're using it to
by js2 2y ago
The potential trouble with $ (even in single-line mode) is that it matches the end of a string BOTH with AND without a newline at the end. If you're using it to ensure the string has no newline before doing something with it, this can lead to trouble.
$ python3 -c 'import re; print("yes" if re.search(r"^foo$", "foo") else "no")'
yes
$ python3 -c 'import re; print("yes" if re.search(r"^foo$", "foo\n") else "no")'
yes
$ python3 -c 'import re; print("yes" if re.search(r"\Afoo\Z", "foo") else "no")'
yes
$ python3 -c 'import re; print("yes" if re.search(r"\Afoo\Z", "foo\n") else "no")'
no
Even if the newline is not problematic, using \A and \Z makes your intentions clearer to the reader, especially if you add re.X and place comments into the pattern.
Asides:
1. Based on syntax, you appear to be testing with python2.
2. With python, re.match is implicitly anchored to the start, so the ^ is redundant. Use re.search or omit the ^.
- medstrom 2y agoCorrect me if I'm wrong, but if you extract a capture group (^foo$), you would get "foo" without the "\n", right? If so, it is not "matching the end of a string" at all. Just end of line. That's exactly as expected in single-line mode, so it's good. May mismatch your expectations in multi-line mode though.
- js2 2y agoThat's right. It all depends on what you're doing with the input string after the match. The point is to be aware of the nuance and to communicate that clearly in the code in cases where it matters.