CS50P: 7. Regular Expressions¶
Regular Expressions / Regexes¶
判断用户是否输入邮箱地址📮¶
if '@' in email
判断字符串中是否有某字符
re¶
re.search( , , )¶
在 string
中查找一个 pattern
patterns¶
基础符号¶
.
表示任意 character
.*
表示 (空)
或 .
或 ..
等等
例如:
finite state machine 运行机制:start \(\Rightarrow\) .
匹配 c-h-a-s-e
循环 \(\Rightarrow\) 匹配 @
\(\Rightarrow\) 匹配 163.com
\(\Rightarrow\) 双线圈,结束,表达式有效
raw string¶
如果想表达 .
(真实存在于文本中的),需要 r
和 \
(tell python not treat . as a special sign)
注意:输入 chase@buaa.edu.
仍会返回 valid
,因为没有要求以 .edu
结尾
进阶符号¶
[abcd]
表示只匹配 abcd 这几个字母,[^a]
表示当前序列不能有 a
缩小范围:
[]
中间不要加空格,逗号等
\w
相当于 [a-zA-Z0-9_]
例如:(edu|org|gov|com|net)
Case Sensitivity¶
flags¶
re.DOTALL
:.
可以匹配换行
使用:if re.search(r"^\w+@\w+\.edu$", email, re.IGNORECASE):
..?(two dots)¶
@subdomain.domain.tld ? (tld = top level domain)
(\w+\.)?
表示 name.
可以出现0次或1次
validate an email address¶
最终版
re--Plus¶
re.match( , , )¶
自动从开头匹配
re.fullmatch( , , )¶
自动匹配开头至结尾
Clean Up User Input¶
Q: user输入 Malan, David
,要求返回 hello, David Malan
- regular expressions 需要引进 re 库
- re.search( , , ) 会返回很多信息
- 括起来的部分会被 captured ,用
.groups()
可以得到
line 5~6 可替换为:
- 下标从1起
line 3~4 :
:=
(walrus operator)assign sth. from right to left & ask boolean question
同时获得 capture 括号的值,并询问 boolean question
Extract User Input¶
Q: prompt users for the url of their Twitter profile, and get their username
思路:https://twitter.com/xxx 中的 xxx 就是 username
问题:
- 输入
www.twitter.com/
xxx/
https
orhttp
- 其他无关输入
My username is ...
re.sub( , , , )¶
pattern: 想替换的部分
repl: 替换成repl
返回新字符串
re.search( , , )¶
进一步:
(?:xxx)
-
yes: use
()
to group -
no: capture
You will not be happy if you try to write out a whole complicated regular expression all at once. Just take these baby steps and make sure it works. You add one more feature make sure it works and hopefully by the end, because you’ve done each of those steps one at a time, the whole thing will make sense to you. --David Malan