Regular Expressions
(aka RegEx)
/ˈrɛɡɛks/ or /ˈrɛdʒɛks/
What is a RegEx?
Example
var str1 = "Chicken soup"
var str2 = "crispy chicken burger"
var str3 = "fish burger"
/chicken/i
Set of characters that represent RULES for SEARCHING or MATCHING text in a string
Regex
Subject
Why bother learning RegEx?
Common Uses
- Data Validations
- Find / Replace text
- Heavily used in parsers
Because I'm sure you have used RegEx before. And if not, you should start using it
Regex Format
/ pattern / flags
Flags
Flags change the default behaviour of your Regex
They are written after the ending forward slash
3 kinds of flags
1. ignore case (i)
2. global (g)
3. multiline (m)
Metacharacters
Characters with special meaning
\ ^ $ . | ? * + ( ) [ {
Note: Can be used as a literal character if preceded by a backslash
Character Class/Set
It matches a character from a specific set. Can be custom of predefined
Examples (Custom CS)
CS of uppercase vowels [AEIOU]
CS of special characters [!@#$%^&*()_+]
CS of a range of characters from a-z [a-z]
CS of all alphabets (uppercase and lowercase) [a-zA-Z]
Note: The order of characters does not matter inside a character set
Note: The only metacharacters inside CS are \ - and ^
Examples (Predefined CS)
\d === [0-9]
\s === space character
\w === [a-zA-Z0-9_ ]
Negated:
\D === [^0-9]
\S === [^\s]
\W === [^a-zA-Z0-9_ ]
Repetation
+ 1 or more
* 0 or more
? 0 or 1
{ a specific number of times
Anchors
Match positions
Word Boundary \b
Beginning of subject ^
End of subject $
Lazy vs Greedy
(Time permitting)
Use of RegEx for
-
Data Validation
-
Text find / replace
-
Making Parsers
Learning Resources
https://www.codeschool.com/courses/breaking-the-ice-with-regular-expressions
Testing Tools:
- http://regexr.com/
- https://regex101.com/
Copy of R
By sarahsga
Copy of R
- 141