如何用JavaScript正则验证多格式Android App ID?
Solution for Matching Android Bundle IDs in JavaScript
Got it, let's fix this regex to cover all the valid Android Bundle ID formats you've encountered on Google Play. Your original regex was too restrictive—it only matched 3-segment IDs starting with com, but we need to support arbitrary prefixes (like eu, au) and any number of segments beyond two.
The Updated Regex
Here's a regex that handles all the cases you mentioned, plus standard valid Bundle IDs:
/^[a-z]+\.[a-z]+(\.[a-z]+)*$/
Breakdown of the Regex
Let's break down what each part does:
^: Anchors the match to the start of the string (prevents partial matches)[a-z]+: Matches the first segment (one or more lowercase letters—coverscom,eu,au, etc.)\.: Matches the dot separator[a-z]+: Matches the second segment (required, so we don't allow invalid IDs likecom.or.example)(\.[a-z]+)*: Matches zero or more additional segments (each starting with a dot followed by lowercase letters)—this is what lets us support 3, 4, or more segments likeau.gh.cc.comorcom.example.jk.com$: Anchors the match to the end of the string (ensures no extra characters are present)
Test Code Snippet
Here's how to implement this in your JavaScript code, with test cases for all your examples:
<script> function validateBundleId(id) { const regexp = /^[a-z]+\.[a-z]+(\.[a-z]+)*$/; return regexp.test(id); } // Test your sample IDs console.log(validateBundleId("com.example.com")); // true console.log(validateBundleId("eu.og.com")); // true console.log(validateBundleId("au.gh.cc.com")); // true console.log(validateBundleId("com.example.jk.com")); // true // Additional edge cases console.log(validateBundleId("com.example")); // true (valid 2-segment ID) console.log(validateBundleId("invalid-id")); // false (no dot separators) console.log(validateBundleId("com.")); // false (incomplete final segment) </script>
Optional Enhancements
- If you need to support uppercase letters (though Google Play typically uses lowercase), add the case-insensitive flag
iat the end:/^[a-z]+\.[a-z]+(\.[a-z]+)*$/i - Android Bundle IDs can also include numbers and underscores in segments (e.g.,
com.my_app.123). To cover those cases, update the character set to[a-z0-9_]:/^[a-z0-9_]+\.[a-z0-9_]+(\.[a-z0-9_]+)*$/i
内容的提问来源于stack exchange,提问作者Shasha
相关产品推荐
相关产品推荐

