Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression matching Android package name

Tags:

regex

android

How can I check if a String is a valid Android package name?

like image 992
Jared Rummler Avatar asked Nov 23 '16 18:11

Jared Rummler


3 Answers

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

like image 56
Jared Rummler Avatar answered Nov 16 '22 07:11

Jared Rummler


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/

like image 35
athenais Avatar answered Nov 16 '22 07:11

athenais


I used this regex and test it depended on official document on android app id

  • It must have at least two segments (one or more dots). Each segment
  • must start with a letter. All characters must be alphanumeric or an
  • underscore [a-zA-Z0-9_].
String regex = "^(?:[a-zA-Z]+(?:\d*[a-zA-Z_]*)*)(?:\.[a-zA-Z]+(?:\d*[a-zA-Z_]*)*)+$" ;
like image 1
Mahmoud Abu Alheja Avatar answered Nov 16 '22 08:11

Mahmoud Abu Alheja