Java Package Declaration in GO
Match Java `package com.example.app;` declarations and capture the dotted package path.
Try it in the GO tester →Pattern
regexGO
^\s*package\s+([a-z][\w]*(?:\.[a-z][\w]*)*)\s*; (flags: m)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)^\s*package\s+([a-z][\w]*(?:\.[a-z][\w]*)*)\s*;`)
input := `package com.example.app;`
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
^\s* allows leading whitespace at line start (m flag enables per-line). package\s+ requires the keyword. ([a-z][\w]*(?:\.[a-z][\w]*)*) captures the package path: each segment must start with a lowercase letter (Java convention) and continue with word characters. \s*; matches the required terminating semicolon.
Examples
Input
package com.example.app;Matches
package com.example.app;
Input
package io.vendor.module.sub;Matches
package io.vendor.module.sub;
Input
// no packageNo match
—