Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/4d879722685e497226a0e50f28deaf61 to your computer and use it in GitHub Desktop.
Save normanlmfung/4d879722685e497226a0e50f28deaf61 to your computer and use it in GitHub Desktop.
python_syntax_regular_expression
import re
def main():
# Email validation
email_address = "[email protected]"
email_pattern = r'^\w+@[a-zA-Z_]+\.[a-zA-Z]{2,3}$'
if re.match(email_pattern, email_address):
print("Valid email address.")
else:
print("Invalid email address.")
# Extracting area code from phone number
phone_number = "(123) 456-7890"
phone_pattern = r'\((\d{3})\)'
match1 = re.match(phone_pattern, phone_number)
if match1:
area_code = match1.group(1)
print("Area code:", area_code)
else:
print("Area code not found.")
# Extracting area code, first part, and second part from text
text = "My phone number is (123) 456-7890."
phone_pattern2 = r'\((\d{3})\) (\d{3})-(\d{4})'
match = re.search(phone_pattern2, text)
if match:
area_code = match.group(1)
first_part = match.group(2)
second_part = match.group(3)
print("Area Code:", area_code)
print("First Part:", first_part)
print("Second Part:", second_part)
else:
print("Phone number not found.")
'''
Multi-part extraction
Month Month Code
January F
February G
March H
April J
May K
June M
July N
August Q
September U
October V
November X
December Z
Examples: https://www.cmegroup.com/markets/cryptocurrencies/bitcoin/bitcoin.quotes.html#venue=globex
BTCH24
BTCJ24
BTCK24
BTCM24
BTCN24
BTCQ24
BTCU24
BTCZ24
BTCH25
BTCU25
BTCZ25
'''
future_code = "BTCH24"
future_code_pattern = r'^(?P<token>[A-Z]{3})(?P<futureMonthCode>[A-Z])(?P<year>\d+)+$'
future_code_match = re.match(future_code_pattern, future_code)
if future_code_match:
token = future_code_match.group("token")
month_code = future_code_match.group("futureMonthCode")
year = int(future_code_match.group("year"))
print(f"futureCode: {future_code}, token: {token}, monthCode: {month_code}, year: {year}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment