HackerRank Java- Regex




Write a class called MyRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address. Use the following definition of an IP address:



  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. import java.util.Scanner;
  4. class Solution{
  5. public static void main(String[] args){
  6. Scanner in = new Scanner(System.in);
  7. while(in.hasNext()){
  8. String IP = in.next();
  9. System.out.println(IP.matches(new MyRegex().pattern));
  10. }
  11. }
  12. }
  13. class MyRegex {
  14. String num = "([01]?\\d{1,2}|2[0-4]\\d|25[0-5])";
  15. String pattern = num + "." + num + "." + num + "." + num;
  16. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube