Go (RE2)

Binary Number Literal in GO

Match binary number literals like `0b1010` or `0B11110000`.

Try it in the GO tester →

Pattern

regexGO
\b0[bB][01]+\b   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\b0[bB][01]+\b`)
	input := `Mask = 0b1010, halfbyte = 0B1111`
	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

\b is a word boundary so we don't match inside identifiers. 0[bB] matches the literal prefix (case-insensitive on the b). [01]+ matches one or more binary digits. Trailing \b prevents matching into adjacent word characters.

Examples

Input

Mask = 0b1010, halfbyte = 0B1111

Matches

  • 0b1010
  • 0B1111

Input

for i := 0; i < 0b1000; i++

Matches

  • 0b1000

Input

no binary here

No match

Same pattern, other engines

← Back to Binary Number Literal overview (all engines)