๐Ÿ”ฐ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))

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

Last updated