Regular Expressions to Validate Google Analytics Tracking Id
Improve Article
Save Article
Like Article
Improve Article
Save Article
Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are:
It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).
The hyphen will come in between the given Google Analytics Tracking Id.
Google Analytics Tracking Id should not start and end with a hyphen (-).
It should not contains whitespaces and other special characters rather than a hyphen symbol.
Examples:
Input: str = ”AB-1234-45” Output: True
Input: str = ”AB-1234-” Output: False Explanation: Google Analytics Tracking Id never ends with a hyphen.
Approach: The problem can be solved based on the following idea:
Create a regex pattern to validate the number as written below: regex = “^[A-Z]{2}[-]{0, 1}[0-9]{1, }[-]{0, 1}[0-9]{1, }$“
Where,
^: Indiactes the start of the string
[A-Z]{2}: This pattern will allow two of the preceding items if they are uppercase alphabets (A-Z).
[-]{0, 1}: This pattern will match zero or one of the preceding items if it is a hyphen symbol.
[0-9]{1}: This pattern will allow one or more than one preceding items if it is a digit.