8 Regular Expressions You Should Know

In computing, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

The key thing to remember about regular expressions is that they are almost read forwards and backwards at the same time. This sentence will make more sense when we talk about matching HTML tags. The delimiters used in the regular expressions are forward slashes, “/”. Each pattern begins and ends with a delimiter. If a forward slash appears in a regex, we must escape it with a backslash: “/”. The eight regular expressions discussed over here allow you to match a(n): username, password, email, hex value (like #fff or #000), slug, URL, IP address, and an HTML tag. Please be notified that these are just examples. It may not work for all cases. You may want to modify as per your need.

  • Matching a Username
    /^[a-z0-9_-]{3,16}$/
  • Matching a Password
    /^[a-z0-9_-]{6,18}$/
  • Matching a Hex Value
    /^#?([a-f0-9]{6}|[a-f0-9]{3})$/
  • Matching a Slug
    /^[a-z0-9-]+$/
  • Matching an Email
    /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/
  • Matching a URL
    /^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/
  • Matching an IP Address
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  • Matching an HTML Tag
    /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

Ref: 8 Regular Expressions You Should Know

Leave a Reply

Your email address will not be published. Required fields are marked *