Regular Expressions (Regex) in JavaScript - Part I

Regular Expressions are used to find a specific pattern within a big glob of text. Regular expressions are also known as regex or regexp among developers.

Read this post for how regular expressions are used in JavaScript methods.

In this post series i'm trying to give you an idea about how to create an regex that matches a particular string.

Very Basic Rules 

  1. Every regular expression literal starts and ends with a forward slash ("/").  
  2. Pattern that we are trying to match goes between those slashes.
  3. After end slash "g", "i", "m" characters can be used as flags. Each letter has different purposes.

Lets start from basic

  1. /a/
    This will match the first "a" character in a string

  2. /a/g
    This will match the all "a" characters in a string."g" flag at the end of regex means get the all matches, dont stop after first match.

  3. /a/gi
    This will match the all "a" characters in a string without case sensitivity (All simple and capital "a" letters)

  4. Dot (".") matches any character except line breaks.
    /./g
    So this will match all characters with empty strings

  5. If you want to match only Dot you have to escape it with a back slash ("\")
    /\./g
    There are characters called meta characters ("[", "{", "(", ")", "\", "$", ".", "|", "?", "*", "+"). If you want to match them with a regex you have to escape it with a "\" as we did to Dot (.)

  6. Quantifiers can be used to represent multiple occurrences of a character instead of typing it many times
    /a{10}/g
    This will match 10 occurrences of "a" ("aaaaaaaaaa").

  7. Using a comma (",") a limit can be given to match
    /a{2,4}/g
    This will match any substring with number of consecutive "a"s are between 2 and 4 including 2 and 4 ("aa", "aaa", "aaaa").

  8. /a{0,}/g
    This will match any number of "a" characters including empty strings

There are some shortcuts

  1. /a*/g is equal to /a{0,}/g
    "*" means any number of characters including 0

  2. /a+/g is equal to /a{1,}/g
    "+" means any number of characters starting from 1

  3. /a?/g is also equal to /a{0,}/g
    "?" means character before that is optional
    • /exp?/g
      This regex will match both "ex" and "exp" because "p" in regex is optional

No comments:

Post a Comment