Python (re)

Single-Line Comment (// or #) in PY

Match single-line comments using either the `//` (C-family) or `#` (shell, Python, Ruby, YAML) marker.

Try it in the PY tester →

Pattern

regexPY
(?://|#).*$   (flags: gm)

Python (re) code

pyPython
import re

pattern = re.compile(r"(?://|#).*$", re.MULTILINE)
input_text = "var x = 1; // assignment\n# python style\ny = 2"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

(?://|#) is a non-capturing group matching either marker. .*$ matches the rest of the line up to the newline. The g flag finds every comment; the m flag makes $ anchor at line boundaries instead of just end-of-string.

Examples

Input

var x = 1; // assignment\n# python style\ny = 2

Matches

  • // assignment
  • # python style

Input

Just a // sample line

Matches

  • // sample line

Input

no comments here

No match

Same pattern, other engines

← Back to Single-Line Comment (// or #) overview (all engines)