Skip to content

Instantly share code, notes, and snippets.

@lifeeric
Created September 2, 2021 18:40
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 lifeeric/5d7aab7a9c8bc18b333b6325054e25f3 to your computer and use it in GitHub Desktop.
Save lifeeric/5d7aab7a9c8bc18b333b6325054e25f3 to your computer and use it in GitHub Desktop.

Finding US Numbers

Not everyone write numbers the same way. Some use sapaces, dashes, dots, and more. You can't find all numbers by just clicking find on page. Thas where RegExr comes in to help.

Summary

I have created an expression to find all US phone numbers on the page. A greate resource to help check your expression would be RegExr. Below I will have instruction on how it was built and works.

Find Any US Number;

/(\+1[ -\d])?(1?)([ -\.]?)(\(?\d{3,5}[ -\.\)]?)[ -\.]?(\d{3}[ -\.]?)(\d{4})/g

Table of Contents

Regex Components

If the expression has the symbol you must use a \ (backslash) \ before to use as a character. Except for - Character Classes

Character Classes

  • The \d matches a digit
  • The \w matches a word
  • The \s matchaes a space
  • The . is a wild card.

Anchors

Anchors are not in my expression but they are good to know.

  • ^ for the start of a string pattern
  • $ for the ends of a string pattern

Quantifiers

I use 3 of the 4 Quantifiers.

  • * will find any characters starting with the first letter.

    • at* will find cat, dog, latitude, mat, dad.
  • ? will find if a character is matching.

    • (\+1[ -\d])? will find any number that starts with +1 with the ? choseing one the the character in [ ]. Like +1 5551234, +1-555-1234, +1347-555-5555
  • {} matches length.

    • {3} matches 3 of the preceding tokens.
    • {3,} 3 or more preceding tokens
    • {3, 5} 3 through 5 (including 3 and 5) preceding tokens.
    • \d{3,5}
      • example expression
      • find 3 digets, 4 or 5 that are together.
  • + matches only single letter.

    • to use as a symbol you need to use a back slash \+

Grouping Constructs

Grouping is used with ()

Groups;

  1. (\+1[ -\d])?
  2. (1?)
  3. ([ -\.]?)
  4. (\(?\d{3,5}[ -\.\)]?)
  5. ([ -\.]?)
  6. (\d{3}[ -\.]?)
  7. (\d{4})

Bracket Expressions

  • [] will match any single character inside.
    • [ -\.\)] space, - , . , ) will be chosen.

The OR Operator

  • | will either left or right.
    • ab | de which is ab or de

Flags

  • /.../g -Gloabl search
  • /aBc/i -Case Insensitive matches AbC
  • /.../m
    • Multiline
  • /.../gim -Flags can be added together.

Test

Example

Author

  • Writen by James Dobbs.

  • Please checkout my GitHub Dobbs96

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