SlideShare a Scribd company logo
1 of 34
Download to read offline
» String Manipulation
» Matching / Validating
» Extracting / Capturing
» Modifying / Substitution

https://www.facebook.com/Oxus20

oxus20@gmail.com

Java
Regular
Expression
PART I
Abdul Rahman Sherzad
Agenda
» What is Regular Expression
» Regular Expression Syntax
˃ Character Classes
˃ Quantifiers
˃ Meta Characters.
» Basic Expression Example
» Basic Grouping Example
» Matching / Validating
» Extracting/Capturing
» Modifying/Substitution
https://www.facebook.com/Oxus20

2
What are Regular Expressions?
» Regular Expressions are a language of string patterns built
into most modern programming languages, Perl, PHP, .NET
and including Java 1.4 onward.
» A regular expression defines a search pattern for strings.
» Regular expressions can be used to search, edit and
manipulate text.
» The abbreviation for Regular Expression is Regex.
3

https://www.facebook.com/Oxus20
Regular Expression Syntax
» Regular Expressions, by definition, are string patterns
that describe text.
» These descriptions can then be used in nearly infinite
ways.
» The basic language constructs include
˃ Character Classes
˃ Quantifiers
˃ Meta Characters.
4

https://www.facebook.com/Oxus20
Character Classes
Character
Class

Explanation and Alternatives

.

Match any character (may or may not match line terminators)

d

Matches a digit, is an alternative for:

D

Matches a non-digit character, is an alternative for:

s

Matches a whitespace character, is an alternative for:

[0-9]
[^0-9]

[ tnx0Bfr]
S

Matches a non-whitespace character, is an alternative for:

w

Match a word character, is an alternative for:

W

Match a non-word character, is an alternative for:

[^s]

[a-zA-Z_0-9]
[^w]

NOTE: in Java, you will need to "double escape" these backslashes "" i.e. "d" should be "d".
5

https://www.facebook.com/Oxus20
Quantifiers
Quantifiers Explanation and Alternatives
*

Match zero or more times, is an alternative for

+

Match one or more times, is an alternative for

{1,}

?

Match no or one times, ? is an alternative for

{0,1}

{n}

Match exactly

{n,}

Match at least

n times,

{n,m}

Match at least

n but not more than m times

{0,}

n number of times

Quantifiers can be used to specify the number or length that part of a
pattern should match or repeat.
https://www.facebook.com/Oxus20

6
Meta Characters
Meta
Characters

Explanation



Escape the next meta-character (it becomes a normal
/ literal character)
Match the beginning of the line

^
.

Match any character (except newline)

$

Match the end of the line (or before newline at the
end)
Alternation for ('or' statement)

|
()

Grouping

[]

Custom character class

Meta-characters are used to group, divide, and perform special
operations in patterns.
https://www.facebook.com/Oxus20

7
Basic Expression: Example I
» Every string is a Regular Expression.
» For example, the string, "I study English", is a regular
expression that will match exactly the string, "I study
English", and will ignore everything else.
» What if we want to be able to find more subject that

we study? We can replace the word English with a
character class expression that will match any
subject. Example on next slide …
8

https://www.facebook.com/Oxus20
Basic Expression: Example II
"I study w+"
» As you can see, the above pattern "I study w+" uses
both a character class and a quantifier.
» The character class "w" says match a word character
» The quantifier "+" says match one or more.

» Now the pattern "I study w+" will match any word in
place of "English" i.e. "I study Programming", "I study
Math", "I study Database", etc.
https://www.facebook.com/Oxus20

9
Example II Demo
public class RegexBasicExampleII {
public static void main(String[] args) {
System.out.println("I study English".matches("I study w+")); // true
System.out.println("I study Programming".matches("I study w+")); // true
System.out.println("I study JAVA".matches("I study w+")); // true
System.out.println("I study: JAVA".matches("I study w+")); // false

}
}
10

https://www.facebook.com/Oxus20
Example II Demo (Alternative)
public class RegexBasicExampleII {
public static void main(String[] args) {
System.out.println("I study English".matches("I study [a-zA-Z_0-9]+")); // true
System.out.println("I study Programming".matches("I study [a-zA-Z_0-9]+")); // true
System.out.println("I study JAVA".matches("I study [a-zA-Z_0-9]+")); // true
System.out.println("I study: JAVA".matches("I study [a-zA-Z_0-9]+")); // false

}
}
11

https://www.facebook.com/Oxus20
Basic Expression: Example III
» But the pattern "I study w+" will not match "I study:
English", because as soon as the expression finds the ":"
character, which is not a word character, it will stop
matching.
» If we want the expression to be able to handle this
situation, then we need to make a small change as follow:

» "I study:? w+"
» Now the pattern "I study:? w+" will match "I study
Programming" and also "I study: Programming"
12

https://www.facebook.com/Oxus20
Example III Demo
public class RegexBasicExampleIII {
public static void main(String[] args) {
System.out.println("I study English".matches("I study:? w+")); // true
System.out.println("I study Programming".matches("I study:? w+")); // true
System.out.println("I study JAVA".matches("I study:? w+")); // true
System.out.println("I study: JAVA".matches("I study:? w+")); // true

}
}
13

https://www.facebook.com/Oxus20
Basic Expression: Example IV
» Also the pattern "I study w+" will not match neither the
string "i study English" and nor "I Study English" , because as
soon as the expression finds the lowercase "i", which is not
equal uppercase "I", it will stop matching.
» If we want the expression to be able to handle this situation
does not care about the case sensitivity then we need to make a

small change as follow:
» "(?i)I study w+"
» Now the pattern "(?i)I study w+" will match both "I STUDY
JAVA" and also "i StUdY JAVA"
https://www.facebook.com/Oxus20

14
Example IV Demo
public class RegexBasicExampleIV {
public static void main(String[] args) {
System.out.println("I study English".matches("(?i)I study w+")); // true
System.out.println("i STUDY English".matches("(?i)I study w+")); // true
System.out.println("I study JAVA".matches("(?i)I study w+")); // true
System.out.println("i StUdY JAVA".matches("(?i)I study w+")); // true

}
}
15

https://www.facebook.com/Oxus20
Regular Expression Basic Grouping
» An important feature of Regular Expressions is the
ability to group sections of a pattern, and provide
alternate matches.
» The following two meta-characters are core parts of
flexible Regular Expressions
˃ | Alternation ('or' statement)
˃ () Grouping
» Consider if we know exactly subjects we are studying, and we
want to find only those subjects but nothing else. Following is
the pattern:
» "I study (Java|English|Programming|Math|Islamic|HTML)"
16

https://www.facebook.com/Oxus20
Regular Expression Basic Grouping
» "I study (Java|English|Programming|Math|Islamic|HTML)"
» The new expression will now match the beginning of the string "I
study", and then any one of the subjects in the group, separated by
alternators, "|"; any one of the following would be a match:
˃ Java
˃ English
˃ Programming
˃ Math
˃ Islamic
˃ HTML
17

https://www.facebook.com/Oxus20
Basic Grouping Demo I (Case Sensitive)
public class BasicGroupingDemoI {

public static void main(String[] args) {
String pattern = "I study (Java|English|Programming|Math|Islamic|HTML)";
System.out.println("I study English".matches(pattern)); // true
System.out.println("I study Programming".matches(pattern)); // true
System.out.println("I study Islamic".matches(pattern)); // true

// english with lowercase letter "e" is not in our group
System.out.println("I study english".matches(pattern)); // false
// CSS is not in our group
System.out.println("I study CSS".matches(pattern)); // false
}
}

18

https://www.facebook.com/Oxus20
Basic Grouping Demo I (Case Insensitive)
public class BasicGroupingDemoI {

public static void main(String[] args) {
String pattern = "(?i)I study (Java|English|Programming|Math|Islamic|HTML)";
System.out.println("I study English".matches(pattern)); // true
System.out.println("I study Programming".matches(pattern)); // true
System.out.println("I study Islamic".matches(pattern)); // true
System.out.println("I study english".matches(pattern)); // true

// CSS is not in our group
System.out.println("I study CSS".matches(pattern)); // false
}
}
19

https://www.facebook.com/Oxus20
Matching / Validating
» Regular Expressions make it possible to find all instances of
text that match a certain pattern, and return a Boolean
value if the pattern is found / not found.
» This can be used to validate user input such as
˃
˃
˃
˃
˃

Phone Numbers
Social Security Numbers (SSN)
Email Addresses
Web Form Input Data
and much more.

» Consider the purpose is to validate the SSN if the pattern is
found in a String, and the pattern matches a SSN, then the
string is an SSN.
20

https://www.facebook.com/Oxus20
SSN Match and Validation
public class SSNMatchAndValidate {
public static void main(String[] args) {
String pattern = "^(d{3}-?d{2}-?d{4})$";
String input[] = new String[5];
input[0]
input[1]
input[2]
input[3]
input[4]

=
=
=
=
=

"123-45-6789";
"9876-5-4321";
"987-650-4321";
"987-65-4321 ";
"321-54-9876";

for (int i = 0; i < input.length; i++)
if (input[i].matches(pattern)) {
System.out.println("Found correct
}
}
OUTPUT:
}
Found correct
}
Found correct
https://www.facebook.com/Oxus20

{
SSN: " + input[i]);

SSN: 123-45-6789
SSN: 321-54-9876

21
SSN Match and Validation Detail
"^(d{3}-?d{2}-?d{4})$"
Regular

// 123-45-6789

Meaning

Expression
^

match the beginning of the line

()

group everything within the parenthesis as group 1

d{3}

match only 3 digits

-?

optionally match a dash

d{2}

match only 2 digits

-?

optionally match a dash

d{4}

match only 4 digits

$

match the end of the line
https://www.facebook.com/Oxus20

22
SSN Match and Validation (Alternative)
public class SSNMatchAndValidateII {
public static void main(String[] args) {
String pattern = "^([0-9]{3}-?[0-9]{2}-?[0-9]{4})$";
String input[] = new String[5];
input[0]
input[1]
input[2]
input[3]
input[4]

=
=
=
=
=

"123-45-6789";
"9876-5-4321";
"987-650-4321";
"987-65-4321 ";
"321-54-9876";

for (int i = 0; i < input.length; i++)
if (input[i].matches(pattern)) {
System.out.println("Found correct
}
}
OUTPUT:
}
Found correct
}
Found correct
https://www.facebook.com/Oxus20

{
SSN: " + input[i]);

SSN: 123-45-6789
SSN: 321-54-9876

23
SSN Match and Validation Detail
"^([0-9]{3}-?[0-9]{2}-?[0-9]{4})$"
Regular

// 123-45-6789

Meaning

Expression
^

match the beginning of the line

()

group everything within the parenthesis as group 1

[0-9]{3}

match only 3 digits

-?

optionally match a dash

[0-9]{2}

match only 2 digits

-?

optionally match a dash

[0-9]{4}

match only 4 digits

$

match the end of the line
https://www.facebook.com/Oxus20

24
Extracting / Capturing
» Capturing groups are an extremely useful feature of
Regular Expression matching that allow us to query
the Matcher to find out what the part of the string was that
matched against a particular part of the regular expression.
» Consider you have a large complex body of text (with an

unspecified number of numbers) and you would like to
extract all the numbers.
» Next Slide demonstrate the example
25

https://www.facebook.com/Oxus20
Extracting / Capturing Numbers
import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ExtractingNumbers {
public static void main(String[] args) {

String text = "Abdul Rahman Sherzad with university ID of 20120 is trying to
demonstrate the power of Regular Expression for OXUS20 members.";
Pattern p = Pattern.compile("d+");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}

OUTPUT:
20120
20

}
}

https://www.facebook.com/Oxus20

26
Extracting / Capturing Explanation
» Import the needed classes
import java.util.regex.Matcher;
import java.util.regex.Pattern;
» First, you must compile the pattern
Pattern p = Pattern.compile("d+");
» Next, create a matcher for a target text by sending a message to your
pattern
Matcher m = p.matcher(text);
» NOTES
˃ Neither Pattern nor Matcher has a public constructor;
+ use static Pattern.compile(String regExpr) for creating pattern
instances
+ using Pattern.matcher(String text) for creating instances of
matchers.
˃ The matcher contains information about both the pattern and the
target text.
https://www.facebook.com/Oxus20

27
Extracting / Capturing
Explanation
» m.find()
˃ returns true if the pattern matches any part of the
text string,
˃ If called again, m.find() will start searching from

where the last match was found
˃ m.find() will return true for as many matches as
there are in the string; after that, it will return false
28

https://www.facebook.com/Oxus20
Extract / Capture Emails
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractEmails {
public static void main(String[] args) {
String text = "Abdul Rahman Sherzad absherzad@gmail.com
on OXUS20 oxus20@gmail.com";
String pattern = "[A-Za-z0-9-_]+(.[A-Za-z0-9-_]+)*@[AZa-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}

OUTPUT:
absherzad@gmail.com
oxus20@gmail.com

}
https://www.facebook.com/Oxus20

29
Modifying / Substitution
» Values in String can be replaced with new values
» For example, you could replace all instances of the
word 'StudentID=', followed by an ID, with a mask to
hide the original ID.
» This can be a useful method of filtering sensitive
information.
» Next Slide demonstrate the example
30

https://www.facebook.com/Oxus20
Mask Sensitive Information
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Substitutions {
public static void main(String[] args) {
String text = "Three student with StudentID=20120, StudentID=20121 and
finally StudentID=20122.";
Pattern p = Pattern.compile("(StudentID=)([0-9]+)");
Matcher m = p.matcher(text);
StringBuffer result = new StringBuffer();
while (m.find()) {
System.out.println("Masking: " + m.group(2));
m.appendReplacement(result, m.group(1) + "***masked***");
}
m.appendTail(result);
System.out.println(result);
}

31

}
https://www.facebook.com/Oxus20
Mask Sensitive Information
(OUTPUT)
» Masking: 20120
» Masking: 20121
» Masking: 20122
» Three student with StudentID=***masked***,
StudentID=***masked*** and finally
StudentID=***masked***.
32

https://www.facebook.com/Oxus20
Conclusion
» Regular Expressions are not easy to use at first
˃ It is a bunch of punctuation, not words
˃ It takes practice to learn to put them together correctly.

» Regular Expressions form a sub-language
˃ It has a different syntax than Java.
˃ It requires new thought patterns
˃ Can't use Regular Expressions directly in java; you have to create Patterns
and Matchers first or use the matches method of String class.

» Regular Expressions is powerful and convenient
to use for string manipulation
˃ It is worth learning!!!
33

https://www.facebook.com/Oxus20
END

34

https://www.facebook.com/Oxus20

More Related Content

What's hot (20)

Array
ArrayArray
Array
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Array in Java
Array in JavaArray in Java
Array in Java
 
C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Array
ArrayArray
Array
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
PHP Basic & Arrays
PHP Basic & ArraysPHP Basic & Arrays
PHP Basic & Arrays
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Array in php
Array in phpArray in php
Array in php
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 

Viewers also liked

TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingLynn Langit
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented ProgrammingAbdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement OXUS 20
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaOXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesOXUS 20
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepOXUS 20
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsOXUS 20
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debugboyw165
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesAbdul Rahman Sherzad
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
 

Viewers also liked (20)

TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids Programming
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debug
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 

Similar to Java Regular Expression PART I

WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaKatrien Verbert
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Java coding pitfalls
Java coding pitfallsJava coding pitfalls
Java coding pitfallstomi vanek
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Word embeddings as a service - PyData NYC 2015
Word embeddings as a service -  PyData NYC 2015Word embeddings as a service -  PyData NYC 2015
Word embeddings as a service - PyData NYC 2015François Scharffe
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
Form validation client side
Form validation client side Form validation client side
Form validation client side Mudasir Syed
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
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
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaPeter Maas
 

Similar to Java Regular Expression PART I (20)

Java
JavaJava
Java
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Tao Showed Me The Way
Tao Showed Me The WayTao Showed Me The Way
Tao Showed Me The Way
 
2.regular expressions
2.regular expressions2.regular expressions
2.regular expressions
 
Java coding pitfalls
Java coding pitfallsJava coding pitfalls
Java coding pitfalls
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Word embeddings as a service - PyData NYC 2015
Word embeddings as a service -  PyData NYC 2015Word embeddings as a service -  PyData NYC 2015
Word embeddings as a service - PyData NYC 2015
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Template
TemplateTemplate
Template
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
Form validation client side
Form validation client side Form validation client side
Form validation client side
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Web Design EJ3
Web Design EJ3Web Design EJ3
Web Design EJ3
 
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
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 

More from OXUS 20

Java Methods
Java MethodsJava Methods
Java MethodsOXUS 20
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersOXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIOXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 

More from OXUS 20 (7)

Java Methods
Java MethodsJava Methods
Java Methods
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 

Recently uploaded

Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 

Recently uploaded (20)

Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 

Java Regular Expression PART I

  • 1. » String Manipulation » Matching / Validating » Extracting / Capturing » Modifying / Substitution https://www.facebook.com/Oxus20 oxus20@gmail.com Java Regular Expression PART I Abdul Rahman Sherzad
  • 2. Agenda » What is Regular Expression » Regular Expression Syntax ˃ Character Classes ˃ Quantifiers ˃ Meta Characters. » Basic Expression Example » Basic Grouping Example » Matching / Validating » Extracting/Capturing » Modifying/Substitution https://www.facebook.com/Oxus20 2
  • 3. What are Regular Expressions? » Regular Expressions are a language of string patterns built into most modern programming languages, Perl, PHP, .NET and including Java 1.4 onward. » A regular expression defines a search pattern for strings. » Regular expressions can be used to search, edit and manipulate text. » The abbreviation for Regular Expression is Regex. 3 https://www.facebook.com/Oxus20
  • 4. Regular Expression Syntax » Regular Expressions, by definition, are string patterns that describe text. » These descriptions can then be used in nearly infinite ways. » The basic language constructs include ˃ Character Classes ˃ Quantifiers ˃ Meta Characters. 4 https://www.facebook.com/Oxus20
  • 5. Character Classes Character Class Explanation and Alternatives . Match any character (may or may not match line terminators) d Matches a digit, is an alternative for: D Matches a non-digit character, is an alternative for: s Matches a whitespace character, is an alternative for: [0-9] [^0-9] [ tnx0Bfr] S Matches a non-whitespace character, is an alternative for: w Match a word character, is an alternative for: W Match a non-word character, is an alternative for: [^s] [a-zA-Z_0-9] [^w] NOTE: in Java, you will need to "double escape" these backslashes "" i.e. "d" should be "d". 5 https://www.facebook.com/Oxus20
  • 6. Quantifiers Quantifiers Explanation and Alternatives * Match zero or more times, is an alternative for + Match one or more times, is an alternative for {1,} ? Match no or one times, ? is an alternative for {0,1} {n} Match exactly {n,} Match at least n times, {n,m} Match at least n but not more than m times {0,} n number of times Quantifiers can be used to specify the number or length that part of a pattern should match or repeat. https://www.facebook.com/Oxus20 6
  • 7. Meta Characters Meta Characters Explanation Escape the next meta-character (it becomes a normal / literal character) Match the beginning of the line ^ . Match any character (except newline) $ Match the end of the line (or before newline at the end) Alternation for ('or' statement) | () Grouping [] Custom character class Meta-characters are used to group, divide, and perform special operations in patterns. https://www.facebook.com/Oxus20 7
  • 8. Basic Expression: Example I » Every string is a Regular Expression. » For example, the string, "I study English", is a regular expression that will match exactly the string, "I study English", and will ignore everything else. » What if we want to be able to find more subject that we study? We can replace the word English with a character class expression that will match any subject. Example on next slide … 8 https://www.facebook.com/Oxus20
  • 9. Basic Expression: Example II "I study w+" » As you can see, the above pattern "I study w+" uses both a character class and a quantifier. » The character class "w" says match a word character » The quantifier "+" says match one or more. » Now the pattern "I study w+" will match any word in place of "English" i.e. "I study Programming", "I study Math", "I study Database", etc. https://www.facebook.com/Oxus20 9
  • 10. Example II Demo public class RegexBasicExampleII { public static void main(String[] args) { System.out.println("I study English".matches("I study w+")); // true System.out.println("I study Programming".matches("I study w+")); // true System.out.println("I study JAVA".matches("I study w+")); // true System.out.println("I study: JAVA".matches("I study w+")); // false } } 10 https://www.facebook.com/Oxus20
  • 11. Example II Demo (Alternative) public class RegexBasicExampleII { public static void main(String[] args) { System.out.println("I study English".matches("I study [a-zA-Z_0-9]+")); // true System.out.println("I study Programming".matches("I study [a-zA-Z_0-9]+")); // true System.out.println("I study JAVA".matches("I study [a-zA-Z_0-9]+")); // true System.out.println("I study: JAVA".matches("I study [a-zA-Z_0-9]+")); // false } } 11 https://www.facebook.com/Oxus20
  • 12. Basic Expression: Example III » But the pattern "I study w+" will not match "I study: English", because as soon as the expression finds the ":" character, which is not a word character, it will stop matching. » If we want the expression to be able to handle this situation, then we need to make a small change as follow: » "I study:? w+" » Now the pattern "I study:? w+" will match "I study Programming" and also "I study: Programming" 12 https://www.facebook.com/Oxus20
  • 13. Example III Demo public class RegexBasicExampleIII { public static void main(String[] args) { System.out.println("I study English".matches("I study:? w+")); // true System.out.println("I study Programming".matches("I study:? w+")); // true System.out.println("I study JAVA".matches("I study:? w+")); // true System.out.println("I study: JAVA".matches("I study:? w+")); // true } } 13 https://www.facebook.com/Oxus20
  • 14. Basic Expression: Example IV » Also the pattern "I study w+" will not match neither the string "i study English" and nor "I Study English" , because as soon as the expression finds the lowercase "i", which is not equal uppercase "I", it will stop matching. » If we want the expression to be able to handle this situation does not care about the case sensitivity then we need to make a small change as follow: » "(?i)I study w+" » Now the pattern "(?i)I study w+" will match both "I STUDY JAVA" and also "i StUdY JAVA" https://www.facebook.com/Oxus20 14
  • 15. Example IV Demo public class RegexBasicExampleIV { public static void main(String[] args) { System.out.println("I study English".matches("(?i)I study w+")); // true System.out.println("i STUDY English".matches("(?i)I study w+")); // true System.out.println("I study JAVA".matches("(?i)I study w+")); // true System.out.println("i StUdY JAVA".matches("(?i)I study w+")); // true } } 15 https://www.facebook.com/Oxus20
  • 16. Regular Expression Basic Grouping » An important feature of Regular Expressions is the ability to group sections of a pattern, and provide alternate matches. » The following two meta-characters are core parts of flexible Regular Expressions ˃ | Alternation ('or' statement) ˃ () Grouping » Consider if we know exactly subjects we are studying, and we want to find only those subjects but nothing else. Following is the pattern: » "I study (Java|English|Programming|Math|Islamic|HTML)" 16 https://www.facebook.com/Oxus20
  • 17. Regular Expression Basic Grouping » "I study (Java|English|Programming|Math|Islamic|HTML)" » The new expression will now match the beginning of the string "I study", and then any one of the subjects in the group, separated by alternators, "|"; any one of the following would be a match: ˃ Java ˃ English ˃ Programming ˃ Math ˃ Islamic ˃ HTML 17 https://www.facebook.com/Oxus20
  • 18. Basic Grouping Demo I (Case Sensitive) public class BasicGroupingDemoI { public static void main(String[] args) { String pattern = "I study (Java|English|Programming|Math|Islamic|HTML)"; System.out.println("I study English".matches(pattern)); // true System.out.println("I study Programming".matches(pattern)); // true System.out.println("I study Islamic".matches(pattern)); // true // english with lowercase letter "e" is not in our group System.out.println("I study english".matches(pattern)); // false // CSS is not in our group System.out.println("I study CSS".matches(pattern)); // false } } 18 https://www.facebook.com/Oxus20
  • 19. Basic Grouping Demo I (Case Insensitive) public class BasicGroupingDemoI { public static void main(String[] args) { String pattern = "(?i)I study (Java|English|Programming|Math|Islamic|HTML)"; System.out.println("I study English".matches(pattern)); // true System.out.println("I study Programming".matches(pattern)); // true System.out.println("I study Islamic".matches(pattern)); // true System.out.println("I study english".matches(pattern)); // true // CSS is not in our group System.out.println("I study CSS".matches(pattern)); // false } } 19 https://www.facebook.com/Oxus20
  • 20. Matching / Validating » Regular Expressions make it possible to find all instances of text that match a certain pattern, and return a Boolean value if the pattern is found / not found. » This can be used to validate user input such as ˃ ˃ ˃ ˃ ˃ Phone Numbers Social Security Numbers (SSN) Email Addresses Web Form Input Data and much more. » Consider the purpose is to validate the SSN if the pattern is found in a String, and the pattern matches a SSN, then the string is an SSN. 20 https://www.facebook.com/Oxus20
  • 21. SSN Match and Validation public class SSNMatchAndValidate { public static void main(String[] args) { String pattern = "^(d{3}-?d{2}-?d{4})$"; String input[] = new String[5]; input[0] input[1] input[2] input[3] input[4] = = = = = "123-45-6789"; "9876-5-4321"; "987-650-4321"; "987-65-4321 "; "321-54-9876"; for (int i = 0; i < input.length; i++) if (input[i].matches(pattern)) { System.out.println("Found correct } } OUTPUT: } Found correct } Found correct https://www.facebook.com/Oxus20 { SSN: " + input[i]); SSN: 123-45-6789 SSN: 321-54-9876 21
  • 22. SSN Match and Validation Detail "^(d{3}-?d{2}-?d{4})$" Regular // 123-45-6789 Meaning Expression ^ match the beginning of the line () group everything within the parenthesis as group 1 d{3} match only 3 digits -? optionally match a dash d{2} match only 2 digits -? optionally match a dash d{4} match only 4 digits $ match the end of the line https://www.facebook.com/Oxus20 22
  • 23. SSN Match and Validation (Alternative) public class SSNMatchAndValidateII { public static void main(String[] args) { String pattern = "^([0-9]{3}-?[0-9]{2}-?[0-9]{4})$"; String input[] = new String[5]; input[0] input[1] input[2] input[3] input[4] = = = = = "123-45-6789"; "9876-5-4321"; "987-650-4321"; "987-65-4321 "; "321-54-9876"; for (int i = 0; i < input.length; i++) if (input[i].matches(pattern)) { System.out.println("Found correct } } OUTPUT: } Found correct } Found correct https://www.facebook.com/Oxus20 { SSN: " + input[i]); SSN: 123-45-6789 SSN: 321-54-9876 23
  • 24. SSN Match and Validation Detail "^([0-9]{3}-?[0-9]{2}-?[0-9]{4})$" Regular // 123-45-6789 Meaning Expression ^ match the beginning of the line () group everything within the parenthesis as group 1 [0-9]{3} match only 3 digits -? optionally match a dash [0-9]{2} match only 2 digits -? optionally match a dash [0-9]{4} match only 4 digits $ match the end of the line https://www.facebook.com/Oxus20 24
  • 25. Extracting / Capturing » Capturing groups are an extremely useful feature of Regular Expression matching that allow us to query the Matcher to find out what the part of the string was that matched against a particular part of the regular expression. » Consider you have a large complex body of text (with an unspecified number of numbers) and you would like to extract all the numbers. » Next Slide demonstrate the example 25 https://www.facebook.com/Oxus20
  • 26. Extracting / Capturing Numbers import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractingNumbers { public static void main(String[] args) { String text = "Abdul Rahman Sherzad with university ID of 20120 is trying to demonstrate the power of Regular Expression for OXUS20 members."; Pattern p = Pattern.compile("d+"); Matcher m = p.matcher(text); while (m.find()) { System.out.println(m.group()); } OUTPUT: 20120 20 } } https://www.facebook.com/Oxus20 26
  • 27. Extracting / Capturing Explanation » Import the needed classes import java.util.regex.Matcher; import java.util.regex.Pattern; » First, you must compile the pattern Pattern p = Pattern.compile("d+"); » Next, create a matcher for a target text by sending a message to your pattern Matcher m = p.matcher(text); » NOTES ˃ Neither Pattern nor Matcher has a public constructor; + use static Pattern.compile(String regExpr) for creating pattern instances + using Pattern.matcher(String text) for creating instances of matchers. ˃ The matcher contains information about both the pattern and the target text. https://www.facebook.com/Oxus20 27
  • 28. Extracting / Capturing Explanation » m.find() ˃ returns true if the pattern matches any part of the text string, ˃ If called again, m.find() will start searching from where the last match was found ˃ m.find() will return true for as many matches as there are in the string; after that, it will return false 28 https://www.facebook.com/Oxus20
  • 29. Extract / Capture Emails import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractEmails { public static void main(String[] args) { String text = "Abdul Rahman Sherzad absherzad@gmail.com on OXUS20 oxus20@gmail.com"; String pattern = "[A-Za-z0-9-_]+(.[A-Za-z0-9-_]+)*@[AZa-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(text); while (m.find()) { System.out.println(m.group()); } } OUTPUT: absherzad@gmail.com oxus20@gmail.com } https://www.facebook.com/Oxus20 29
  • 30. Modifying / Substitution » Values in String can be replaced with new values » For example, you could replace all instances of the word 'StudentID=', followed by an ID, with a mask to hide the original ID. » This can be a useful method of filtering sensitive information. » Next Slide demonstrate the example 30 https://www.facebook.com/Oxus20
  • 31. Mask Sensitive Information import java.util.regex.Matcher; import java.util.regex.Pattern; public class Substitutions { public static void main(String[] args) { String text = "Three student with StudentID=20120, StudentID=20121 and finally StudentID=20122."; Pattern p = Pattern.compile("(StudentID=)([0-9]+)"); Matcher m = p.matcher(text); StringBuffer result = new StringBuffer(); while (m.find()) { System.out.println("Masking: " + m.group(2)); m.appendReplacement(result, m.group(1) + "***masked***"); } m.appendTail(result); System.out.println(result); } 31 } https://www.facebook.com/Oxus20
  • 32. Mask Sensitive Information (OUTPUT) » Masking: 20120 » Masking: 20121 » Masking: 20122 » Three student with StudentID=***masked***, StudentID=***masked*** and finally StudentID=***masked***. 32 https://www.facebook.com/Oxus20
  • 33. Conclusion » Regular Expressions are not easy to use at first ˃ It is a bunch of punctuation, not words ˃ It takes practice to learn to put them together correctly. » Regular Expressions form a sub-language ˃ It has a different syntax than Java. ˃ It requires new thought patterns ˃ Can't use Regular Expressions directly in java; you have to create Patterns and Matchers first or use the matches method of String class. » Regular Expressions is powerful and convenient to use for string manipulation ˃ It is worth learning!!! 33 https://www.facebook.com/Oxus20