JavaScript Regular Expressions (Regex) - Beginner to Expert
Regular Expressions(Regex) - JavaScript - Beginner to Expert
When I started teaching regular expression (regex or regexp), there were no sufficient resources! Being in this industry for almost 23 years now, and after exploring an ocean of digital content, I must say - Regex needs to be explained in a more simplified way.
Let’s discuss and understand a concept which is very important in the present scenario.
I’ve seen students and even working professionals getting confused with the basic concepts of Regex. Having said that, I must also mention that Regular expression (regex) can be overwhelming sometimes. It is imperative for you to grasp the core concepts thoroughly at your own pace.
Course will help you to clear your concepts by understanding the fundamentals the way they should be understood. The course will guide and help you in a step by step way to apply regex techniques and reach the desired solution.
I have used more than 165+ coding examples to explain the concepts and included advanced level interview questions asked by companies. I will teach from scratch and bring you up to the level of an expert - Guaranteed!
What are javaScript Regular Expressions?
Regular expressions allow you to check a string of characters like an e-mail address or password for patterns, to see so if they match the pattern defined by that regular expression and produce actionable information
Introduction to regular expressions in JavaScript
A regular expression is a string that describes a pattern e.g., email addresses and phone numbers.
In JavaScript, regular expressions are objects. JavaScript provides the built-in RegExp type that allows you to work with regular expressions effectively.
Regular expressions are useful for searching and replacing strings that match a pattern. They have many useful applications.
For example, you can use regular expressions to extract useful information in web scraping like product prices. Or you can use regular expressions to validate form fields like email addresses and phone numbers.
Creating a Regular Expression
There are two ways to create a regular expression in Javascript Regular Expression . It can be either created with RegExp constructor, or by using forward slashes ( / ) to enclose the pattern.
Regular Expression Constructor:
Syntax: new RegExp(pattern)
Example:
var regexConst = new RegExp('abc');
Regular Expressions(Regex) - JavaScript - All Levels - 2022 ( Udemy )Nirmal Joshi, Founder CEO,Corporate Trainer,Programming AficionadoCrack any interview related to Regular Expressions (Regex) with 165+ coding exercises asked in fortune 1000 companies. 4.6 (44 ratings)37 lectures, 3 hours
javaScript Regular Expression Literal:
Syntax: /pattern/flags
Example:
var regexLiteral = /abc/;
- Here the flags are optional, I will explain these later in this article.
There might also be cases where you want to create regular expressions dynamically, in which case regex literal won’t work, so you have to use a regular expression constructor.
No matter which method you choose, the result is going to be a regex object. Both regex objects will have same methods and properties attached to them
Since forward slashes are used to enclose patterns in the above example, you have to escape the forward slash ( / ) with a backslash ( ) if you want to use it as a part of the regex.
javaScript Regular Expressions Methods
There are mainly two methods for testing regular expressions.
RegExp.prototype.test()
This method is used to test whether a match has been found or not. It accepts a string which we have to test against regular expression and returns true or false depending upon if the match is found or not.
For example:
var regex = /hello/;var str = 'hello world';var result = regex.test(str);console.log(result);// returns true
RegExp.prototype.exec()
This method returns an array containing all the matched groups. It accepts a string that we have to test against a regular expression.
For example:
var regex = /hello/;var str = 'hello world';var result = regex.exec(str);console.log(result);// returns // 'hello' -> is the matched pattern.// index: -> Is where the regular expression starts.// input: -> Is the actual string passed.
We are going to use the test() method in this article.
Simple Regex Patterns
It is the most basic pattern, which simply matches the literal text with the test string. For example:
var regex = /hello/;console.log(regex.test('hello world'));// true
Regular Expressions(Regex) - JavaScript - All Levels - 2022 ( Udemy )Nirmal Joshi, Founder CEO,Corporate Trainer,Programming AficionadoCrack any interview related to Regular Expressions (Regex) with 165+ coding exercises asked in fortune 1000 companies. 4.6 (44 ratings)37 lectures, 3 hours
Special Characters In javaScript Regular Expressions
Up until now we’ve created simple javaScript Regular Expressions patterns. Now, let’s tap into the full power of regular expressions when handling more complex cases.
For example, instead of matching a specific email address let’s say we’d like to match a number of email addresses. That’s where special characters come into play.
There are special symbols and characters that you have to memorize in order to fully understand the regular expressions.
Flags:
Regular expressions have five optional flags or modifiers. Let’s discuss the two most important flags:
- — Global search, don’t return after the first match
- — Case-insensitive search
You can also combine the flags in a single regular expression. Note that their order doesn’t have any effect on the result.
Let’s look at some code examples:
Regular Expression Literal — Syntax /pattern/flags
var regexGlobal = /abc/g;console.log(regexGlobal.test('abc abc'));// it will match all the occurence of 'abc', so it won't return // after first match.var regexInsensitive = /abc/i;console.log(regexInsensitive.test('Abc'));// returns true, because the case of string characters don't matter // in case-insensitive search.
Regular Expression Constructor — Syntax new RegExp('pattern', 'flags')
var regexGlobal = new RegExp('abc','g')console.log(regexGlobal.test('abc abc'));// it will match all the occurence of 'abc', so it won't return // after first match.var regexInsensitive = new RegExp('abc','i')console.log(regexInsensitive.test('Abc'));// returns true, because the case of string characters don't matter // in case-insensitive search.
Character groups:
Character set — A character set is a way to match different characters in a single position, it matches any single character in the string from characters present inside the brackets. For example:
var regex = /ear/;console.log(regex.test('tear'));// returns trueconsole.log(regex.test('bear'));// return trueconsole.log(regex.test('fear'));// return false
Note — All the special characters except for caret (^) (Which has entirely different meaning inside the character set) lose their special meaning inside the character set.
Negated character set — It matches anything that is not enclosed in the brackets. For example:
var regex = /ear/;console.log(regex.test('tear'));// returns falseconsole.log(regex.test('bear'));// return falseconsole.log(regex.test('fear'));// return true
Ranges — Suppose we want to match all of the letters of an alphabet in a single position, we could write all the letters inside the brackets, but there is an easier way and that is ranges. For example: will match all the letters from a to h. Ranges can also be digits like or capital letters like .
var regex = /ear/;console.log(regex.test('fear'));// returns trueconsole.log(regex.test('tear'));// returns true
Meta-characters — Meta-characters are characters with a special meaning. There are many meta character but I am going to cover the most important ones here.
- — Match any digit character ( same as ).
- — Match any word character. A word character is any letter, digit, and underscore. (Same as ) i.e alphanumeric character.
- — Match a whitespace character (spaces, tabs etc).
- — Match a tab character only.
- — Find a match at beginning or ending of a word. Also known as word boundary.
- — (period) Matches any character except for newline.
- — Match any non digit character (same as ).
- — Match any non word character (Same as ).
- — Match a non whitespace character.
Quantifiers: — Quantifiers are symbols that have a special meaning in a regular expression.
Regular Expressions(Regex) - JavaScript - All Levels - 2022 ( Udemy )Nirmal Joshi, Founder CEO,Corporate Trainer,Programming AficionadoCrack any interview related to Regular Expressions (Regex) with 165+ coding exercises asked in fortune 1000 companies. 4.6 (44 ratings)37 lectures, 3 hours
- — Matches the preceding expression 1 or more times.
var regex = /d+/;console.log(regex.test('8'));// trueconsole.log(regex.test('88899'));// trueconsole.log(regex.test('8888845'));// true
- —Matches the preceding expression 0 or more times.
var regex = /go*d/;console.log(regex.test('gd'));// trueconsole.log(regex.test('god'));// trueconsole.log(regex.test('good'));// trueconsole.log(regex.test('goood'));// true
- — Matches the preceding expression 0 or 1 time, that is preceding pattern is optional.
var regex = /goo?d/;console.log(regex.test('god'));// trueconsole.log(regex.test('good'));// trueconsole.log(regex.test('goood'));// false
- — Matches the beginning of the string, the regular expression that follows it should be at the start of the test string. i.e the caret (^) matches the start of string.
var regex = /^g/;console.log(regex.test('good'));// trueconsole.log(regex.test('bad'));// falseconsole.log(regex.test('tag'));// false
- — Matches the end of the string, that is the regular expression that precedes it should be at the end of the test string. The dollar ($) sign matches the end of the string.
var regex = /.com$/;console.log(regex.test('test@testmail.com'));// trueconsole.log(regex.test('test@testmail'));// false
- — Matches exactly N occurrences of the preceding regular expression.
var regex = /go{2}d/;console.log(regex.test('good'));// trueconsole.log(regex.test('god'));// false
- — Matches at least N occurrences of the preceding regular expression.
var regex = /go{2,}d/;console.log(regex.test('good'));// trueconsole.log(regex.test('goood'));// trueconsole.log(regex.test('gooood'));// true
- — Matches at least N occurrences and at most M occurrences of the preceding regular expression (where M > N).
var regex = /go{1,2}d/;console.log(regex.test('god'));// trueconsole.log(regex.test('good'));// trueconsole.log(regex.test('goood'));// false
Alternation X|Y — Matches either X or Y. For example:
var regex = /(green|red) apple/;console.log(regex.test('green apple'));// trueconsole.log(regex.test('red apple'));// trueconsole.log(regex.test('blue apple'));// false
Note — If you want to use any special character as a part of the expression, say for example you want to match literal + or ., then you have to escape them with backslash ( ).
For example:
var regex = /a+b/; // This won't workvar regex = /a+b/; // This will workconsole.log(regex.test('a+b')); // true
Advanced
(x) — Matches x and remembers the match. These are called capturing groups. This is also used to create sub expressions within a regular expression. For example :-
var regex = /(foo)bar1/;console.log(regex.test('foobarfoo'));// trueconsole.log(regex.test('foobar'));// false
1 remembers and uses that match from first subexpression within parentheses.
(?:x) — Matches x and does not remember the match. These are called non capturing groups. Here 1 won’t work, it will match the literal 1.
var regex = /(?:foo)bar1/;console.log(regex.test('foobarfoo'));// falseconsole.log(regex.test('foobar'));// falseconsole.log(regex.test('foobar1'));// true
x(?=y) — Matches x only if x is followed by y. Also called positive look ahead. For example:
var regex = /Red(?=Apple)/;console.log(regex.test('RedApple'));// true
In the above example, match will occur only if Redis followed by Apple.
Let’s practice some of the concepts that we have learned above.
var regex = /^d{10}$/;console.log(regex.test('9995484545'));// true
Let’s break that down and see what’s going on up there.
- If we want to enforce that the match must span the whole string, we can add the quantifiers ^ and $. The caret ^ matches the start of the input string, whereas the dollar sign $ matches the end. So it would not match if string contain more than 10 digits.
https://itexamtools.com/regular-expressionsregex-javascript-beginner-to-expert/
Comments
Post a Comment