Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Regular Expression re{ n, m} Metacharacter in Java
The subexpression/metacharacter “re{ n, m}” matches at least n and at most m occurrences of the preceding expression.
Example 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "xyy{2,4}";
String input = "xxyyzxxyyyyxyyzxxyyzz";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}
Output
Number of matches: 1
Example 2
The following Java program reads name value from the user and, it only allows 1 to 20 characters.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[] ) {
//Regular expression to match characters at least 1 almost 20
String regex = "[a-zA-Z]{1,20}";
Scanner sc = new Scanner(System.in);
System.out.println("Enter students name:");
String name = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(name);
if(m.matches()) {
System.out.println("Name is appropriate");
} else {
System.out.println("Name is inappropriate");
}
}
}
Output 1
Enter students name: Mouktika Name is appropriate
Output 2
Enter students name: ka 34 Name is inappropriate
Output 3
Enter students name: Sri Veera Venkata Satya Sai Suresh Santosh Samrat Name is in inappropriate
Advertisements