Lab 15 Java_2k23
Lab 15 Java_2k23
Lab Manual - 15
OOP
Lab-15: Regular Expressions in Java
Laboratory 15:
Statement Purpose:
After this lab, students will be able to use Regular Expressions in Java.
Regular Expressions:
Java regular expressions are a powerful tool for developers working with text manipulation and
validation. In this lab, you will learn how to use Java regular expressions for pattern matching
and manipulation.
Usage: Regular expressions provide a powerful means to match and manipulate text patterns
in strings. They are widely used for tasks such as input validation, search and replace
operations, and parsing text data. By using regular expressions, you can simplify complex code,
improve performance, and increase the readability of your applications.
For pattern matching with the regular expressions, Java offers java.util.regex bundle.
java.util.regex bundle.
This provides regular expressions with three classes and a single interface. The classes Matcher
and Pattern are usually used in standard Java language.
Pattern Class:
• public static Pattern compile(String regex): Compiles the given regex into a pattern.
• public Matcher matcher(CharSequence input): Creates a matcher that will match the
given input against the pattern.
Matcher Class:
• public boolean find(): Attempts to find the next subsequence of the input sequence that
matches the pattern.
• public boolean matches(): Attempts to match the entire input sequence against the
pattern.
• public int start(): Returns the start index of the previous match.
• public int end(): Returns the index of the last matched character.
MatchResult Interface:
Output:
PatternSyntaxException Class:
The complete program of Showing the PatternSyntaxException class example is listed below.
import java.util.regex.*;;
public class PatternSyntaxExceptionExample {
public static void main(String[] args) {
try {
String regex = "["; // invalid regex
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern);
}
catch (PatternSyntaxException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
In the above example program, we use the invalid syntax of regex. So, when we run the
program, it generates the PatternSyntaxException: Unclosed character class near index 0;
Java.util.regex.Pattern:
The compile() method is used to compile the given regular expression into a pattern.
This method takes a pattern string value as the argument which needs to be compiled.
Example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
public static void main(String[] args) {
// Get the string value to be checked
Pattern p = Pattern.compile(".o");
//Matcher string for
Matcher m = p.matcher("to");
boolean m1 = m.matches();
System.out.println(m1);
}
}
Output:
True
The matches() method is used to check whether the given string matches the given regular
expression or not. This method returns the boolean value true if the string matches the regex
otherwise, it returns false. If the syntax is invalid, then this method throws
PatternStateException.
• regex: This argument is the regular expression value that has to be checked from
the string.
• String: This string value has to be checked from the regex through the matches()
method.
The complete program of the public boolean matches(regex, String) method is listed below.
Example:
import java.util.regex.Pattern;
public class PatternClassMatchesExample{
public static void main(String args[]) {
System.out.println(Pattern.matches("[bad]", "abcd"));
System.out.println(Pattern.matches("[as]", "a"));
System.out.println(Pattern.matches("[att]", "atttna"));
}
}
Output:
java.util.regex.Matcher:
By calling the matcher method, you get a Matcher object on a Pattern object.
The matches method is used to check whether the pattern string matches with the matcher string
or not. It returns the boolean value. If the string matches, it returns true otherwise false. It does
not take any argument. It does not throw any exception.
import java.util.regex.*;
public class MatchesMethodExample {
public static void main(String[] args) {
boolean result;
// Get the string value to be checked
String value1 = "^OOP.+";
Output:
Question: If the value2 variable contains only string “OOP”, then what will be the output?
The start() method is used to get the start subsequence index. This method does not take any
argument. It returns the index of the first character matched. If the operation fails, it throws
IllegalStateException.
import java.util.regex.*;
public class StartMethodExample {
public static void main(String[] args) {
Engr. Sidra Shafi 4
SSShafiemester
Lab-15: Regular Expressions in Java
try {
// Get the string value to be checked
String value1 = "Game";
}
}
catch(IllegalStateException e)
{
System.out.println(" ex" +e.getMessage());
}
}
}
Output:
22
The find method is used to find the next subsequence of the input sequence that finds the
pattern. It returns a boolean value. If the input string matches, then it returns true otherwise
returns false. This method does not take any argument. This method does not throw any
exception.
import java.util.regex.*;
public class FindMethodExample {
Output:
true
false
The find(int start) method is used to find the next subsequence of the input sequence that finds
the pattern according to the given argument. It returns a boolean value. This method throws
IndexOutOfBoundException if the given argument is less than zero or greater than the length
of the string.
import java.util.regex.*;
public class FindExample2 {
public static void main(String args[]) {
// Get the regex to be checked
String value = "web";
String value1 = "Game";
}
}
Output:
The end() method is used to get the end subsequence index. This method does not take any
argument. It returns the index of the last character matched0.
import java.util.regex.*;
public class EndMethodExample {
public static void main(String[] args) {
Pattern p=Pattern.compile("Java lab");
Engr. Sidra Shafi 6
SSShafiemester
Lab-15: Regular Expressions in Java
Output:
MetaCharacters:
Some characters (“metacharacters”) have a special meaning when they appear in a regular
expression. Here is the complete list:
<([{\^-=$!|]})?*+.>
If we want to match any of these characters, we need to “escape” them by prefixing them with
a \ character. Since \ is itself a metacharacter, it needs to be escaped to include it in a string
literal representing a regular expression.
Logical Operators:
Character Classes:
Bracket notation can be used to create sets such that any character in the set will be considered
a match.
Quantifiers:
Write a Java Program to find a pattern from file and print it. Print Line numbers along
with markers indicating which portion of the line matched. Marks:10
Expected Output:
File contents:
************