๐ฐlookaround
๐ง under construction
JS โฉ value โฉ object โฉ regex โฉ pattern โฉ lookaround
(?=...) // Positive lookahead (match the position before the specified regex)
(?!...) // Negative lookahead (donโt match, as above)
(?<=...) // Positive lookbehind (match the position after the specified regex)
(?<!...) // Negative lookbehind (don't match, as above)
const {log} = console;
/*
Symbols
-------
โข ? : lookaround
โข = : positive
โข ! : negative (NOT)
โข < : lookbehind
lookahead: X(?=Y)
------------------
match X (followed "immediately" by Y):
match X ("lookahead" for Y)
lookahead: X(?=Y)(?=Z)
-----------------------
match X (followed "immediately" by Y & Z)
match X ("lookahead" for Y & Z)
negative lookahead: X(?!Y)
---------------------------
match X (NOT followed "immediately" by Y)
match X ("negative lookahead" for Y)
Lookbehind: (?<=Y)X
--------------------
match X ("immediately" following Y)
Negative Lookbehind: (?<!Y)X
-----------------------------
match X (NOT "immediately" following Y)
*/
// โฑ space โญโฎ
let str = "1 turkey costs $30โฌ";
// โฐโโโโ .*30 โโโโโโฏ
[
// lookahead
// ----------
// โญXโฎ Y
str.match(/\d+(?=โฌ)/), // ["30"]
// โญXโฎ โญโฎ โญโโโฎ
str.match(/\d+(?=\s)(?=.*30)/), // ["1"]
str.match(/\d+(?=.*30)(?=\s)/), // ["1"]
str.match(/\d+(?=30)(?=\s)/), // โญ๏ธ null
// (no digits are followed "immediately" by "30")
// negative lookahead
// ------------------
str.match(/\d+\b(?!โฌ)/g), // ["1"]
// โฐโโฏโฐโฏ โ
// lookbehind:
// ----------
// escaped $ โโญโฎ โญโโฎ
str.match(/(?<=\$)\d+/), // ["30"]
].forEach(x => log(x))
codepen โฉ regex: lookaround
codewars โฉ Regex Password Validation
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
examples
Password Validation
// Look ahead
// -----------
// (?=.*\d) : at least one digit.
// (?=.*[a-z]) : at least one lower case.
// (?=.*[A-Z]) : at least one upper case.
// [0-9a-zA-Z]{6,}: at least 6 alphanumeric characters.
// /^...$/ : whole line
function validate(password) {
return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,}$/.test(password);
}
words with (-) or (')
// (?=[a-zA-Z'-]*[a-zA-Z]): at least one alphabet character
//
/(?=[a-zA-Z'-]*[a-zA-Z])[a-zA-Z'-]+/g
RegEx โฉ words with (-) and (')
Last updated