vl - regular expressions
Introduction to Regular Expressions
Regular expressions (regex) are a powerful tool for searching and matching patterns within text.
Overview of Regular Expressions
Regular expressions consist of:
A pattern to match text.
Zero or more modifiers known as flags that provide additional instructions on how to use the pattern.
Historical Context
Perl:
Perl is a popular language known for pattern matching.
The lecturer does not prefer Perl due to its cryptic syntax.
JavaScript:
JavaScript borrows its regex syntax from Perl.
Components of Regular Expressions
A regex pattern can be simple or complex:
Example of a simple pattern: matching a verbatim string, such as "my name."
Complex patterns often involve formats like phone numbers, credit card numbers, or valid email addresses.
Using JavaScript for Regular Expressions
JavaScript provides a constructor called
RegExpto create regular expression objects.Regular expressions can be defined in two main ways:
Using the
newkeyword to create an object.Using literal notation.
Example of Regex Pattern
Pattern Structure Example:
Regex:
j.*tExplanation:
Starts with 'j'.
Ends with 't'.
Contains zero or more characters in between.
Matches examples: "just", "jet", "jot".
Components of the Pattern:
The period
.means any character.The asterisk
*signifies zero or more of the preceding element.
Properties of RegExp Objects
Regular Expression Properties in JavaScript:
global property: If set to false, the search stops at the first match.
ignore case property: Negates case sensitivity in matching.
multiline property: Allows matching that spans more than one line (defaults to false).
last index property: Indicates the position to start searching (defaults to zero).
source property: Contains the regex pattern being matched.
Testing Regular Expressions
Example of Case Sensitivity in JavaScript:
If a search phrase starts with 'J' and ends with 'T', using lower case 'j' and 't' results in no match because regex is case sensitive.
To make the regex case insensitive, the
iflag is added.Example Regex:
/j.*t/i
String methods that accept regex:
match: Returns an array of matches (use global modifier to retrieve all matches).
search: Returns the index of the first match.
replace: Allows replacing matched text.
Practical Example of String Matching
Define a string:
let s = "Hello, JavaScript world!"Match character
a:The first occurrence appears at index 6.
Using match to find all occurrences requires the global flag.
Demonstrating Replace Method
Regex can be used to replace characters in a string.
Example: Removing all capital letters, replacing them with blank spaces.
Splitting Strings Using Regular Expressions
Use
splitmethod to separate values in a string:Example: Given a CSV string
"1,2,3,4"Use
splitmethod with comma,as the pattern to split into an array:string.split(/,/).
Conclusion
Encouragement for users to explore and practice with regular expressions to understand their capabilities.