Skip to content

Instantly share code, notes, and snippets.

@yi-mei-wang
Last active October 23, 2019 05:35
Show Gist options
  • Save yi-mei-wang/3073646c271797c1eecf63589b560d00 to your computer and use it in GitHub Desktop.
Save yi-mei-wang/3073646c271797c1eecf63589b560d00 to your computer and use it in GitHub Desktop.
Regular expressions in Python

Regex in Python

  1. Use the regex library by typing

    import re
  2. A regex pattern looks like this:

    r"<pattern>"
    r"(\d{4}(\-?)){4}"
  3. re.match() vs re.search()?

    1. re.match() only checks from the beginning
    2. re.search() checks anywhere in the string
    3. Example:
      >>> re.match("c", "abcdef")    # No match
      >>> re.search("c", "abcdef")   # Match
    4. https://docs.python.org/3/library/re.html#search-vs-match
  4. re.match() returns the first occurrence, while re.findall() returns all the matches

  5. re.sub(A, B, target_string) replaces A with B in target_string

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