Go (RE2)

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

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

Try it in the GO tester →

Pattern

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

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?m)(?://|#).*$`)
	input := `var x = 1; // assignment\n# python style\ny = 2`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

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)