Write a java program to validate string using Regular Expression. Given a string (s) apply the following rules.
- String should be only four characters long.
2. First character can be an alphabet or digit.
3. Second character must be uppercase ‘R’.
4. Third character must be a number between 0-9.
If all the conditions are satisifed then print TRUE else print FALSE.
The return type is the boolean formed based on rules.
Input and Output Format:
Input consists of a string.
Output consists of TRUE or FALSE .
Refer sample output for formatting specifications.
Sample Input 1:
vR4u
Sample Output 1:
TRUE
Sample Input 2:
vRau
Sample Output 2:
FALSE
Sample Input 3:
vrau
Sample Output 3:
FALSE
java program to validate string using Regular Expression
package com.demo;
import java.util.*;
public class Main {
public static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
String n = sc.nextLine();
System.out.println(display(n));
}
public static String display(String s) {
String w = "FALSE";
if (s.length() == 4 && (Character.isDigit(s.charAt(0)) || Character.isAlphabetic(s.charAt(0)))
&& s.charAt(1) == 'R') {
if (Character.isDigit(s.charAt(2)))
w = "TRUE";
}
return w;
}
}