Regular Expressions

以前总觉得正则表达式好难 ಥ_ಥ,遇到的时候总刻意逃避,从没认真搞明白。今天又看了coursera 课程,发现其实很好理解。


在python中,regular expressions 没有像 strings, lists 或者是dictionaries一样被内置于基本语言中,所以在使用正则表达式时要导入 re 模块。

常用的正则表达式字符:
Regular Expressions

正则表达式的使用

下面直接举例说明。

re.search()

Regular Expressions
Regular Expressions
re.search(): to see if a string matches a regular expression, similar to using the find() method for strings

re.findall()

Regular Expressions
re.findall(): to extract portions of a string that match your regular expression, similar to a combination of find() and slicing: var[5:10]

Greedy vs. Non-Greedy Matching

Regular Expressions
Regular Expressions

示例

Regular Expressions

示例

Regular Expressions

示例

Regular Expressions

括号的使用

提取完整邮箱地址:
Regular Expressions
提取邮箱地址后半部分:
做法一:
Regular Expressions
做法二:
Regular Expressions

Regex-Handout
Regex-Lecture

相关文章: