SlideShare uma empresa Scribd logo
1 de 18
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

Mais conteúdo relacionado

Mais procurados

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 

Mais procurados (20)

Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
L11 array list
L11 array listL11 array list
L11 array list
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Java exception
Java exception Java exception
Java exception
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
ASP.NET Core
ASP.NET CoreASP.NET Core
ASP.NET Core
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 

Destaque (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
 

Semelhante a Regular Expressions in Java

Regular Expression
Regular ExpressionRegular Expression
Regular Expression
Bharat17485
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
phanleson
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
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
 

Semelhante a 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
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

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