Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Last active April 23, 2021 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardocanelas/6436933b92be9c8662277a2573f7956b to your computer and use it in GitHub Desktop.
Save ricardocanelas/6436933b92be9c8662277a2573f7956b to your computer and use it in GitHub Desktop.
Regex - Basic information

Reference

Meta Sequences:

  • . (a dot) It denotes “any character except a newline”

Quantifiers:

  • + to the match one character after another.
  • ? is a quantifier by itself (zero or one), but if added after another quantifier (or even itself) it gets another meaning – it switches the matching mode from greedy --> to --> lazy.

Quantifiers

Greedy search

let regex = /".+"/g
let str = `a "witch" and her "broom" is one...`

str.match(regex) 
// "witch" and her "broom"

Lazy mode

It means: “repeat minimal number of times”.

let regex = /".+?"/g
let regexAlternativeApproach = /"[^"]+"/g;
let str = `a "witch" and her "broom" is one...`

str.match(regex) 
// "witch"
// "broom"

Inspirations

@ricardocanelas
Copy link
Author

ricardocanelas commented Jun 12, 2020

g guarda um state de lastIndex. Não é exatamente regex, mas a implementação do js. Se tem o ^ e $ tem pouco motivo pra usar /g. - https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment