Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7cea966

Browse files
Create Regex
1 parent 7d05629 commit 7cea966

File tree

1 file changed

+53
-0
lines changed
  • automate_the_boring_stuff

1 file changed

+53
-0
lines changed

‎automate_the_boring_stuff/Regex

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Pages 147 - 153 in ATBS textbook
2+
# Pattern Matching and Regular Expressions
3+
4+
## Ex... Phone Number
5+
# 919-675-9338 <- A phone number
6+
# 4,150,000 <- Not a phone number
7+
8+
9+
##Non-RegEx Example
10+
# def isPhoneNumber(text):
11+
# if len(text) != 12:
12+
# return False #not phone number
13+
# for i in range(0,3):
14+
# if not text[i].isdecimal():
15+
# return False #no area code
16+
# if text[3] != '-':
17+
# return False #missing dash
18+
# for i in range(4,7):
19+
# if not text[i].isdecimal():
20+
# return False #no first 3 digits
21+
# if text[7] != '-':
22+
# return False #missing second dash
23+
# for i in range(8,12):
24+
# if not text[i].isdecimal():
25+
# return False #missing last 4 digits
26+
# return True
27+
#
28+
# print(isPhoneNumber('919-675-9338'))
29+
#
30+
#
31+
# message = 'Call me at 415-555-1011 tomorrow, or at 919-675-9338 over the weekend for my personal line'
32+
# foundNumber = False
33+
# for i in range(len(message)):
34+
# chunk = message[i:i+12]
35+
# if isPhoneNumber(chunk):
36+
# print('Phone number found:', chunk)
37+
# foundNumber = True
38+
# if not foundNumber:
39+
# print('Could not find any phone numbers.')
40+
41+
42+
43+
44+
# So now, let's decrease the lines of code we need for that
45+
import re
46+
message = 'Call me at 415-555-1011 tomorrow, or at 919-675-9338 over the weekend.'
47+
48+
# phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
49+
# mo = phoneNumRegex.search(message)
50+
# print(mo.group())
51+
52+
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
53+
print(phoneNumRegex.findall(message))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /