Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Regular Expression that validates input username:
^[_\.]\d+[a-zA-Z]*_?$
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class AlienUsername { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); for (int i = 0; i < testCases; i++) { String input = scanner.next(); if(input.matches("[_\\.]\\d+[a-zA-Z]*_?")) { System.out.println("VALID"); } else { System.out.println("INVALID"); } } scanner.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function processData(input) { var lines = input.split("\n"); for(var i = 1; i < lines.length; i++) { if(lines[i].match(/^[_\.]\d+[a-z]*_?$/ig)) { console.log("VALID"); } else { console.log("INVALID"); } } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import scala.io.Source object AlienUsername extends App { val usernames = Source.stdin.getLines().drop(1) println(usernames.map(validateUsername).mkString("\n")) def validateUsername(name: String): String = { if (name.matches("[_\\.]\\d+[a-zA-Z]*_?")) return "VALID" else return "INVALID" } } |
Ruby
1 2 3 4 5 6 7 8 9 |
n = gets.to_i n.times do name = gets.to_s.strip if /[_\.]\d+[a-zA-Z]*_?/ =~ name puts "VALID" else puts "INVALID" end end |