Python (re)

Java Package Declaration in PY

Match Java `package com.example.app;` declarations and capture the dotted package path.

Try it in the PY tester →

Pattern

regexPY
^\s*package\s+([a-z][\w]*(?:\.[a-z][\w]*)*)\s*;   (flags: m)

Python (re) code

pyPython
import re

pattern = re.compile(r"^\s*package\s+([a-z][\w]*(?:\.[a-z][\w]*)*)\s*;", re.MULTILINE)
input_text = "package com.example.app;"
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

^\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 package

No match

Same pattern, other engines

← Back to Java Package Declaration overview (all engines)