news.volyx.in

Regex character "$" doesn't mean "end-of-string" (sethmlarson.dev)

437 points by BerislavLopac · 879 days ago · 366 comments on HN

Article summary

The article discusses the behavior of the regex character '$' in Python, which can match either the end of a string or a trailing newline before the end of a string when multiline mode is disabled. This behavior is not what most people expect, as they assume '$' always means 'end-of-string'. The article also explores how different regex flavors, such as Perl and ECMAScript, handle this situation. The author suggests using 'z' or 'Z' to match the end of a string without a newline.

Main themes

  • Regex behavior
  • Multiline mode
  • End-of-string matching
  • Regex flavors
  • Python regex
  • Character escaping

What commenters say

  • The behavior of '$' in Python's regex is a design decision that may not align with user expectations, but it is not necessarily wrong.
  • The difference in behavior between regex flavors, such as Perl and Python, can lead to confusion and unexpected results.
  • Some argue that '$' should always match the end of a string, while others believe it should match the end of a line, even when multiline mode is disabled.
  • The use of 'z' or 'Z' can provide a more explicit way to match the end of a string without a newline, avoiding potential issues with '$'.
  • The history of regex development and the influence of different programming languages have contributed to the variations in regex behavior across flavors.
  • The importance of understanding the specific regex flavor being used and its quirks cannot be overstated, as it can significantly impact the accuracy of pattern matching.
  • Some commenters argue that the behavior of '$' in Python is not a bug, but rather a consequence of the language's design choices and the trade-offs made to support different use cases.
  • The discussion highlights the need for careful consideration of the regex flavor and its implications when working with regular expressions in different programming languages.