Skip to content
the poor coder

Hackerrank Valid Username Regular Expression Solution

Poor Man
Published
Updated
Reading time
1 min read

You are updating the username policy on your company's internal networking platform. According to the policy, a username is considered valid if all the following constraints are satisfied:

  • The username consists of  to  characters inclusive. If the username consists of less than  or greater than  characters, then it is an invalid username.
  • The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters , uppercase characters , and digits .
  • The first character of the username must be an alphabetic character, i.e., either lowercase character  or uppercase character .

Update the value of regularExpression field in the UsernameValidator class so that the regular expression only matches with valid usernames.

Input Format.

The first line of input contains an integer , describing the total number of usernames. Each of the next  lines contains a string describing the username. The locked stub code reads the inputs and validates the username.

Constraints.

  • The username consists of any printable characters.

Output Format.

For each of the usernames, the locked stub code prints Valid if the username is valid; otherwise Invalid each on a new line.

Sample Input 0.

Text
8
Julia
Samantha
Samantha_21
1Samantha
Samantha?10_2A
JuliaZ007
Julia@007
_Julia007

Sample Output 0.

Text
Invalid
Valid
Valid
Invalid
Invalid
Valid
Invalid
Invalid

Explanation 0.

Refer diagram in the challenge statement.

Solution in java8#

Approach 1.

Python

class UsernameValidator {
    /*
     * Write regular expression here.
     */
    public static final String regularExpression = "[a-zA-Z](\\w){7,29}";
}

Approach 2.

Python

class UsernameValidator {
    /*
     * Write regular expression here.
     */
    public static final String regularExpression = "^[A-Za-z]\\w{7,29}$";
}

Approach 3.

Python

class UsernameValidator {
    /*
     * Write regular expression here.
     */
    public static final String regularExpression = "\\p{Alpha}(\\w|_){7,29}";
}

Keep going

2020

Hackerrank Java String Tokens Solution

Given a string, , matching the regular expression [A-Za-z !,?._'@]+, split the string into tokens. We define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed…

2020

Hackerrank Java Anagrams Solution

Two strings, and , are called anagrams if they contain all the same characters in the same frequencies. For example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA. Complete the function in the editor. If and…

ESC