Graduate Program KB

Regex

  • Look Ahead: Assertion for when matching things look ahead and say a match has happened if it occurs after it
    • ^ Beginning of String, match if at the start of string
    • $ End of String, match if at the end of string
    var msg = "Hello World";

    //Look Aheads
    console.log(msg.match(/(l.)/g)); //['ll','ld']
    console.log(msg.match(/(l.)$/g)); //['ld'] $ for end of string
    console.log(msg.match(/(l.)(?=o)/g)); //['ll'] positive lookahead, if pattern "o" is after the l.
    console.log(msg.match(/(l.)(?!o)/g)); // ['lo','ld']Negative lookahead return matches that dont have the pattern "o" in the matches

    //Look Behinds
    console.log(msg.match(/(?<=e)(l.)/g)); //['ll'] match l. if preceded with an e
    console.log(msg.match(/(?<!e)(l.)/g)); //['lo','ld'] match l. if e is not behind it

Named Capture Groups

  • You can use named variables to store different regex matches
    var msg = "Hello World"

    console.log(msg.match(/(?<cap>l.)/).groups); //{ cap: 'll' }

.all Mode

  • Flag to add to regex
  • /s = .all Mode
  • /u = unicode awareness Mode
  • /g
    msg.match(/pattern/<flags>)