Write a Javaprogram that prints all strings defined by a regular expressionup to
ID: 3798081 • Letter: W
Question
Write a Javaprogram that prints all strings defined by a regular expressionup to a givenlength. Assume the alphabet ={1,0}. Prompt the user to enter a regular expression and an integer n. Print all the strings, with length n, defined by the regular expression.Use console based I/O. [The empty string can be printed with the Unicode “u03B5”, but Unicode may not be supported in some environments].
A samplerun of the program is shown bellow.
Regular expression: 01*|(10)*
n: 5
-------Strings in the language -------
0
01
10
011
0111
1010
01111
Explanation / Answer
This program will get the user input for number n and print the result
import java.util.regex.*;
import java.util.Scanner;
/*
* Checks for invalid characters
* in email addresses
*/
class RegularExpression {
public static void main(String[] args)
throws Exception {
String input = "^01*|(10)*$";
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt();
Pattern p1 = Pattern.compile(input);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
for (int i = 1; i <= n; i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
}
}
catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.