Created
August 18, 2023 15:10
-
-
Save suhailgupta03/99050d7f6957dc599113233561739d8e to your computer and use it in GitHub Desktop.
Author
suhailgupta03
commented
Aug 18, 2023
let string = "apple";
let pattern = /ap{2}le/g
// p{2} means match the character p exactly 2 times.
console.log(string.match(pattern)); // Output: ["pp"]
let pattern2 = /ap{2,4}le/g
// p{2,4} means match the character p at least 2 times and at most 4 times.
console.log(string.match(pattern2))
let pattern3 = /ap*le/g
// p* means match the character p "0 or more times".
console.log(string.match(pattern3))
let pattern4 = /ap+le/g
// p+ means match the character p "1 or more times".
console.log(string.match(pattern4))
let pattern5 = /ap?le/g
// p? means match the character p "0 or 1 times".
console.log(string.match(pattern5))
/*?= is a part of regular expression syntax in JavaScript. It is used to create a positive lookahead.
A lookahead is a type of zero-width assertion that allows you to match a pattern only if it is followed by another pattern, without including the second pattern in the match.
Here's an example:*/
let string = "apple banana mango";
let regex = /apple(?=\sbanana)/;
console.log(string.match(regex)); // Output: [ 'apple', index: 0, input: 'apple banana mango', groups: undefined ]
/*
In this case, the regex /apple(?=\sbanana)/ matches "apple" only if it is followed by " banana". The space before "banana" in (?=\sbanana) is necessary to match the space in the original string.
It's important to note that the lookahead pattern \sbanana (meaning "a space followed by 'banana'") is not included in the match result. The match only includes "apple". This is what's meant by "zero-width": the lookahead doesn't consume characters in the string, but only asserts whether a match is possible.
*/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment