SlideShare a Scribd company logo
e-mail: mrdevilbynature@gmail.com
 a Regular Expression (abbreviated as RegEx) is

a sequence of characters that forms a search
pattern, mainly for use in string matching.

 RegEx is kind of a language within a language.
Metacharacters:
A metacharacter is a character that has a special meaning to a
computer program, such as a regular expression engine.
A few metacharacters supported by Java RegEx Engine are:
 d

: Represents a digit.

 D

: Represents a non-digit



s

: Represents a whitespace.



S

: Represents a non-whitespace

 w

: Represents a word Character
(letters, numbers or an underscore).

 W

: Represents a non-word Character.

 “.”

: Represents any character
The basic structure of a RegEx is bounded by the below
mentioned classes.







Literal escape
Grouping
Range
Union
Intersection

x
[...]
a-z
[a-e][i-u]
[a-z&&[aeiou]]

The union operator denotes a class that contains every
character that is in at least one of its operand classes.
The intersection operator denotes a class that contains
every character that is in both of its operand classes.
Used to specify the number of occurrences.
 X?
 X*
 X+
 X{n}
 X{n,}
 X{n,m}

X, once or not at all
X, zero or more times
X, one or more times
X, exactly n times
X, at least n times
X, at least n but not more
than m times
 [abc]

Searches for a‟s or b‟s or
c‟s.
 d+
Searches for a Number.
 0[xX]([0-9a-fA-F])+ Searches for a
Hexadecimal Number.
 [a-fn-s]
Searches for a character
between a to f OR n to s.
 The Classes that help in implementing RegEx in

Java are:

Pattern class
2. Matcher class
(Both the classes are present in the java.util.regex
package)
1.
A regular expression, specified as a string, must first
be compiled into an instance of this class.
The resulting pattern can then be used to create a
Matcher object that can match arbitrary character
sequences against the regular expression.
All of the state involved in performing a match
resides in the matcher, so many matchers can share
the same pattern.
An engine that performs match operations on a character
sequence by interpreting a Pattern.
A Matcher object is created from a pattern by invoking the
pattern's matcher method.
Once created, a matcher can be used to perform three
different kinds of match operations:
 The matches method attempts to match the entire input
sequence against the pattern.
 The lookingAt method attempts to match the input sequence,
starting at the beginning, against the pattern.
 The find method scans the input sequence looking for the next
subsequence that matches the pattern.
This method starts at the beginning of this matcher's region, or,
if a previous invocation of the method was successful and the
matcher has not since been reset, at the first character not
matched by the previous match.
Each of these methods returns a boolean indicating success or
failure.
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaababaab");
The compile method in the Pattern class is a
static method which takes a Regular Expression
in the form of a String as the argument
A Matcher object is created by invoking the
matcher method of the Pattern class

[The matcher method is a Non-static method, so
it requires a Pattern object for its invocation]
Once a match has been found by using one of the
matches, lookingAt and find method, the following
Matcher class methods can be used to display the
results:
 public int start()

Returns the start index of the
previous match.

 public int end()

Returns the offset after the
character matched.

 public String group()

Returns the input
subsequence matched by
the previous match.

last
import java.util.regex.*;
public class Regex
{
public static void main(String[] arg)
{
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
if(m.matches())
System.out.println(m.start()+" "+m.end()+" "+m.group());
}
}
Output:
0 6 aaaaab
import java.util.regex.*;
public class Regex
{
public static void main(String[] arg)
{
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("b aab");
if(m.lookingAt())
System.out.println(m.start()+" "+m.end()+" "+m.group());
}
}
Output:
0 1 b
import java.util.regex.*;
public class Regex
{
public static void main(String[] arg)
{
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("ab aabcba");
while(m.find())
System.out.println(m.start()+" "+m.end()+" "+m.group());
}
}
Output:
0 2 ab
3 6 aab
7 8 b
Writing the statement:
String regex=“d”;
would produce a COMPILER ERROR!
Whenever the compiler sees a „‟ inside a String, it expects
the next character to be an escape sequence.
The way to satisfy the compiler is to use double backslashes.
The statement:
String regex=“d”;
is a valid RegEx metacharacter in the form of a String.
Suppose, if we want the dot (.) to represent its usual meaning
while writing a Regular Expression as a String.
String s = “.”;

would be considered as a legal RegEx
metacharacter

Also,
String s=“.”;

would be considered as an
illegal escape sequence by the
compiler
The workaround is to use double backslashes :

String s=“.”;
Represents a dot, and not some RegEx metacharacter.
 Java api documentation SE6
 SCJP – Kathy Sierra and Bert Bates
 Wikipedia
Regular Expressions in Java

More Related Content

What's hot

Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Wrapper classes
Wrapper classes Wrapper classes
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
String Handling
String HandlingString Handling
String Handling
Bharat17485
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Java reflection
Java reflectionJava reflection
Java reflection
NexThoughts Technologies
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 

What's hot (20)

Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Method overriding
Method overridingMethod overriding
Method overriding
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Generics
GenericsGenerics
Generics
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
String Handling
String HandlingString Handling
String Handling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 

Viewers also liked

Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
Satya Narayana
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Thomas Langston
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
wayn
 
Java 2
Java 2Java 2
Expresiones regulares
Expresiones regularesExpresiones regulares
Expresiones regulares
Jordan-P
 
Control structures i
Control structures i Control structures i
Control structures i
Ahmad Idrees
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
Abhilash Nair
 
Graph theory 1
Graph theory 1Graph theory 1
Graph theory 1
Tech_MX
 
Java
Java Java
Java I/O
Java I/OJava I/O
Operators in java
Operators in javaOperators in java
Operators in java
Ravi_Kant_Sahu
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
vishaljot_kaur
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
Operators in java
Operators in javaOperators in java
Operators in java
Muthukumaran Subramanian
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
Jin Castor
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 

Viewers also liked (16)

Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
 
Java 2
Java 2Java 2
Java 2
 
Expresiones regulares
Expresiones regularesExpresiones regulares
Expresiones regulares
 
Control structures i
Control structures i Control structures i
Control structures i
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Graph theory 1
Graph theory 1Graph theory 1
Graph theory 1
 
Java
Java Java
Java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to Regular Expressions in Java

Regex1.1.pptx
Regex1.1.pptxRegex1.1.pptx
Regex1.1.pptx
VigneshK635628
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
Bharat17485
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
anjani pavan kumar
 
Java scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java ScannerJava scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java Scanner
Edward Nyang'ali
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
DarellMuchoko
 
Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regex
Yongqiang Li
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
phanleson
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
info673628
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
Mukesh Tekwani
 
SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)
Logan Palanisamy
 
Generics collections
Generics collectionsGenerics collections
Generics collections
Yaswanth Babu Gummadivelli
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
Sowri Rajan
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
GaneshRaghu4
 

Similar to Regular Expressions in Java (20)

Regex1.1.pptx
Regex1.1.pptxRegex1.1.pptx
Regex1.1.pptx
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Java scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java ScannerJava scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java Scanner
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
 
Introduction to Boost regex
Introduction to Boost regexIntroduction to Boost regex
Introduction to Boost regex
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 

Recently uploaded

The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 

Recently uploaded (20)

The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 

Regular Expressions in Java

  • 2.  a Regular Expression (abbreviated as RegEx) is a sequence of characters that forms a search pattern, mainly for use in string matching.  RegEx is kind of a language within a language.
  • 3. Metacharacters: A metacharacter is a character that has a special meaning to a computer program, such as a regular expression engine. A few metacharacters supported by Java RegEx Engine are:  d : Represents a digit.  D : Represents a non-digit  s : Represents a whitespace.  S : Represents a non-whitespace  w : Represents a word Character (letters, numbers or an underscore).  W : Represents a non-word Character.  “.” : Represents any character
  • 4. The basic structure of a RegEx is bounded by the below mentioned classes.      Literal escape Grouping Range Union Intersection x [...] a-z [a-e][i-u] [a-z&&[aeiou]] The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.
  • 5. Used to specify the number of occurrences.  X?  X*  X+  X{n}  X{n,}  X{n,m} X, once or not at all X, zero or more times X, one or more times X, exactly n times X, at least n times X, at least n but not more than m times
  • 6.  [abc] Searches for a‟s or b‟s or c‟s.  d+ Searches for a Number.  0[xX]([0-9a-fA-F])+ Searches for a Hexadecimal Number.  [a-fn-s] Searches for a character between a to f OR n to s.
  • 7.  The Classes that help in implementing RegEx in Java are: Pattern class 2. Matcher class (Both the classes are present in the java.util.regex package) 1.
  • 8. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
  • 9. An engine that performs match operations on a character sequence by interpreting a Pattern. A Matcher object is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:  The matches method attempts to match the entire input sequence against the pattern.  The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.  The find method scans the input sequence looking for the next subsequence that matches the pattern. This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match. Each of these methods returns a boolean indicating success or failure.
  • 10. Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaababaab"); The compile method in the Pattern class is a static method which takes a Regular Expression in the form of a String as the argument A Matcher object is created by invoking the matcher method of the Pattern class [The matcher method is a Non-static method, so it requires a Pattern object for its invocation]
  • 11. Once a match has been found by using one of the matches, lookingAt and find method, the following Matcher class methods can be used to display the results:  public int start() Returns the start index of the previous match.  public int end() Returns the offset after the character matched.  public String group() Returns the input subsequence matched by the previous match. last
  • 12. import java.util.regex.*; public class Regex { public static void main(String[] arg) { Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab"); if(m.matches()) System.out.println(m.start()+" "+m.end()+" "+m.group()); } } Output: 0 6 aaaaab
  • 13. import java.util.regex.*; public class Regex { public static void main(String[] arg) { Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("b aab"); if(m.lookingAt()) System.out.println(m.start()+" "+m.end()+" "+m.group()); } } Output: 0 1 b
  • 14. import java.util.regex.*; public class Regex { public static void main(String[] arg) { Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("ab aabcba"); while(m.find()) System.out.println(m.start()+" "+m.end()+" "+m.group()); } } Output: 0 2 ab 3 6 aab 7 8 b
  • 15. Writing the statement: String regex=“d”; would produce a COMPILER ERROR! Whenever the compiler sees a „‟ inside a String, it expects the next character to be an escape sequence. The way to satisfy the compiler is to use double backslashes. The statement: String regex=“d”; is a valid RegEx metacharacter in the form of a String.
  • 16. Suppose, if we want the dot (.) to represent its usual meaning while writing a Regular Expression as a String. String s = “.”; would be considered as a legal RegEx metacharacter Also, String s=“.”; would be considered as an illegal escape sequence by the compiler The workaround is to use double backslashes : String s=“.”; Represents a dot, and not some RegEx metacharacter.
  • 17.  Java api documentation SE6  SCJP – Kathy Sierra and Bert Bates  Wikipedia