How can I check if a String is a valid 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/
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_]*)*)+$" ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With