Regex Pattern for Validating Length in Java 2024 - Java Technical Interview


Regex Pattern Program for Validating Length

        Here we are going to check whether the given String has only certain number length using the Regex Pattern matching logic in Java. The steps are


Logical Theory :

  • Check for Length: Ensure the number has exactly 10 digits.


Regex Pattern for Validation :

    1. Regex: ^.{10}$

    2. Explanation:

              ^ asserts the start of the string.

              .{10} matches exact length10.

              $ asserts the end of the string.


Code :

package com.dinatechy.challange;


import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class LenghtPattern {

public static void main(String[] args) {

// Pattern for validate length

String content = "DinaTechy";// length - 9

Pattern pattern = Pattern.compile("^.{9}$");

Matcher matcher = pattern.matcher(content);

if(matcher.matches())// return true based on condition

System.out.println("Matched");

else

System.out.println("Not Matched");

}


}

Scenario 1 :

Input :

DinaTechy

Output :

Matched

Scenario 2 :

Input :

DinaTechy0

Output :

Not Matched


Follow us for more useful Java Regex Pattern Programs...

Comments

Popular posts from this blog

Finding Second largest number in Array - Java - TCS - Technical Interview

Checking Character only in String - Java 2024 - MNC - Technical Interview

Object Class in Java | Article | Solution Maker - Blog