Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Lab 15 Java_2k23

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab 15 Java_2k23

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / Lab Task, Mid Exam, Final


projects of varying complexities. Exam, Quiz, Assignment, P2 / C2 3
Semester Project
2 Use modern tool and languages. Lab Task, Semester
P2 5
Project
3 Demonstrate an original solution of Lab Task, Semester
A2 8
problem under discussion. Project
4 Work individually as well as in Lab Task, Semester A2 9
teams Project

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: Represents a compiled regular expression. This class provides methods to


compile and match regular expressions.
• Matcher: Represents an engine that performs match operations on a character sequence
using a compiled pattern. This class provides methods to manipulate and query the
results of a match operation.

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:

The java.util.regex.MatchResult interface represents the result of a match operation.

Engr. Sidra Shafi 1


SSShafiemester
Lab-15: Regular Expressions in Java

The complete program of the regex package is listed below.


import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
System.out.println(Pattern.matches(".y", "toy"));
System.out.println(Pattern.matches("s..", "sam"));
System.out.println(Pattern.matches(".a", "mia")); } }

Output:

PatternSyntaxException Class:

PatternSyntaxException is an unresolved exception object which means a syntax error in a


normal speaking pattern.

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:

A Pattern object is a compiled representation of a regular expression.

Methods of Pattern Class:

static Pattern compile(String regex)


Engr. Sidra Shafi 2
SSShafiemester
Lab-15: Regular Expressions in Java

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.

Syntax: static Pattern compile(String regex)

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

public boolean matches(regex, String)

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.

This method takes two arguments.

• 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:

Engr. Sidra Shafi 3


SSShafiemester
Lab-15: Regular Expressions in Java

java.util.regex.Matcher:

By calling the matcher method, you get a Matcher object on a Pattern object.

Methods of Matcher Class:

public boolean matches():

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.

Syntax: public boolean matches();

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.+";

// Create a pattern from regex


Pattern pattern = Pattern.compile(value1);

// Get the String value to be matched


String value2 = "OOP Lab related to Regular Expressions";
// Create a matcher for the input String
Matcher matcher = pattern.matcher(value2);

// Get the current matcher state


System.out.println("result : " + matcher.matches());
}
}

Output:

Question: If the value2 variable contains only string “OOP”, then what will be the output?

public int start() Method:

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";

// Create a pattern from regex


Pattern pattern = Pattern.compile(value1);

// Get the String value to be matched


String value2 = "Java is also used for Game development";
// Create a matcher for the input String
Matcher matcher = pattern.matcher(value2);
// Get the first index of match result
while (matcher.find()) {
System.out.println(matcher.start());

}
}
catch(IllegalStateException e)
{
System.out.println(" ex" +e.getMessage());
}
}
}
Output:
22

public boolean find() Method

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 {

public static void main(String[] args) {


// Get the regex to be checked
String value = "Csharp";
String value1 = "Java world";

// Create a string from regex


Pattern pattern = Pattern.compile(value);
Pattern pattern1 = Pattern.compile(value1);

// Get the String for matching


String matchString = "Csharp is used for web developemnt";
String matchString1 ="Java Programming";

// Create a matcher for the String


Matcher match = pattern.matcher(matchString);
Matcher match1 = pattern1.matcher(matchString1);
//find() method
System.out.println(match.find());
System.out.println(match1.find());
}
}
Engr. Sidra Shafi 5
SSShafiemester
Lab-15: Regular Expressions in Java

Output:
true

false

public boolean find(int start) Method:

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";

// Create a string from regex


Pattern pattern = Pattern.compile(value);
Pattern pattern1 = Pattern.compile(value1);

// Get the String for matching


String matchString = "Csharp is used for web development";
String matchString1 = "Java is used for Game development";

// Create a matcher for the String


Matcher match = pattern.matcher(matchString);
Matcher match1 = pattern1.matcher(matchString1);
//find() method
System.out.println(match.find(3));
System.out.println(match1.find(60));

}
}

Output:

public int end() Method:

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

Matcher m=p.matcher("Java lab dr");


while (m.find()) {
//Get the last index of match result
System.out.println("string matches till index " +m.end());
}
}}

Output:

string matches till index 8

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.

Engr. Sidra Shafi 7


SSShafiemester
Lab-15: Regular Expressions in Java

Predefined Character Classes:

Quantifiers:

Engr. Sidra Shafi 8


SSShafiemester
Lab-15: Regular Expressions in Java

Boundary Matchers: Restrict where a match can be made:

Lab Tasks Marks:10

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:

************

Engr. Sidra Shafi 9


SSShafiemester

You might also like