Skip to content

Regex for Python Comment — Pattern, Examples & Caveats

Pattern flags: gm
#.*$

This pattern matches Python single-line comments beginning with # and running to the end of the line. Python has no block comment syntax, so # comments (and docstrings, which are strings) are the only comment form. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It uses the gm flag(s). Apply it across text to collect every occurrence. It matches # inside string literals (e.g. '#notacomment') as a false positive — use Python's tokenize module for accurate comment handling. Docstrings (triple-quoted strings) are not comments and are not matched by this pattern. The shebang line (#!...) is matched as a comment, which is usually fine but may need special handling. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • # — a literal hash starting the comment
  • .* — any characters except newline
  • $ — end of line (per-line with the m flag)
  • g flag — find all comments
  • m flag — multiline so $ matches each line end

What it matches

# notex = 1 # trailing#!/usr/bin/env python3

What it does not match

print('hello')no hash herex = '#notacomment'

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • It matches # inside string literals (e.g. '#notacomment') as a false positive — use Python's tokenize module for accurate comment handling.
  • Docstrings (triple-quoted strings) are not comments and are not matched by this pattern.
  • The shebang line (#!...) is matched as a comment, which is usually fine but may need special handling.

Code examples

JavaScript
const re = /#.*$/gm;
const text = "see # note and more";
const found = [...text.matchAll(re)].map(m => m[1] ?? m[0]);
// found holds every extracted occurrence
Python
import re

rx = re.compile(r"#.*$", re.M)
text = "see # note and more"
found = rx.findall(text)   # every occurrence (groups if present)
Java
import java.util.regex.*;

Pattern p = Pattern.compile("#.*$", Pattern.MULTILINE);
Matcher m = p.matcher("# note");
boolean ok = m.find();   // scan for occurrences
PHP
<?php
$subject = "# note";
if (preg_match_all('/#.*$/m', $subject, $m)) {
    // $m[0] is the full match; $m holds every occurrence
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

Does Python have block comments?

No — Python only has # line comments. Triple-quoted strings are sometimes used as block comments but are actually string literals (docstrings), not comment syntax.

Why does it match # inside a string?

The regex cannot distinguish string literals from code, so a # in a string looks like a comment. Use the tokenize module to identify real comments accurately.

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →