Regular expression matching Android package name

A valid Android package name is described in the AndroidManifest documentation for the package attribute:

The name should be unique. The name may contain uppercase or lowercase letters ('A' through 'Z'), numbers, and underscores ('_'). However, individual package name parts may only start with letters.

See: https://developer.android.com/guide/topics/manifest/manifest-element.html#package


The following regular expression will match a valid Android package name:

^([A-Za-z]{1}[A-Za-z\d_]*\.)+[A-Za-z][A-Za-z\d_]*$

Example usage:

String regex = "^([A-Za-z]{1}[A-Za-z\\d_]*\\.)+[A-Za-z][A-Za-z\\d_]*$";
List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
for (PackageInfo packageInfo : packages) {
  if (packageInfo.packageName.matches(regex)) {
    // valid package name, of course.
  }
}

For a detailed explanation of the regex, see: https://regex101.com/r/EAod0W/1


going off of @skeeve 's comment, you can use \w in place of [a-z0-9_]

Full Regex:

/^[a-z]\w*(\.[a-z]\w*)+$/i

Explanation:

i

global pattern flag for case insensitive (ignores case of [a-zA-Z])

^

asserts position at start of a line

[a-z]

matches a single character in the range between a (index 97) and z (index 122) (case insensitive)

\w*

\w matches any word character (equal to [a-zA-Z0-9_])

* quantifier matches between zero and unlimited times, as many times as possible

(.[a-z]\w*)+

parentheses define a group

\.

matches the character . literally (case insensitive)

[a-z] see above

\w* see above

+

quantifier matches between one and unlimited times, as many times as possible

$

asserts position at the end of a line

https://regex101.com/

Tags:

Regex

Android