正则表达式
正则表达式是一个非常强的功能.日常查找和替换数据都是非常好的.
工具
有一些工具 可视化正则表达式 和 表达式测试工具.也可以用sublime的查找和替换来进程测试.
正则表达式的语法
简单匹配
t:匹配t字符,其他字符也是类似
模糊匹配
.:任意字符(换行除外)
\w: a-zA-Z0-9_
\W: 除了\w以外的所有字符
\d:数字字符 0-9
\D:非数字字符
\s:空格字符 \t\n\f\r\p
\S:所有非空格字符
还有其他的\n\r\f\v\p\t
其中有一个逻辑是:如果\+大写字母是\+小写字母的反例
模块化(将多个字符变成一个整体元素)
():将多个字符用小括号括起来,这样能够变成一个整体单元来处理.支持嵌套
循环
+ :表示前面的元素重复出现1+次
*:表示前面元素出现任意次 0+次
?:表示前面的元素出现0or1次
{n}:表示前面的元素出现n次
{n,m}:表示前面的元素出现n到m次
?这个一般修饰在+*后面,表示降低这种循环的优先级,让后续的条件的优先级更高.
复用
() + \n : 正则表达式是从左到右进行解析的.可以在左侧使用()标记一个匹配元素.然后在表达式后侧使用 \n进行复用.这里需要借用模块化.
条件
?:表示 0,1次选择
[tT]:表示t和T任意匹配一个
(car|bus)car和bus任意匹配一个
(?=) or (?<=) or(?!) or (?!=)当遇到某种情况后停下来.
\b : 间隙: \w和\W之间的情况
\B: \w和\w \W和\W之间的情况
还有一种嵌套条件表达式很多语言的正则表达式不支持.
替换截取
()选中+$(n)进行重新排列和截取
练习题
习题
Lesson 1: An Introduction, and the ABCs
abc.*

Lesson 1½: The 123s
.*?\d{3}.*

Lesson 2: The Dot
.*?\.

Lesson 3: Matching specific characters
[cmf]an

Lesson 4: Excluding specific characters
[^b]og

Lesson 5: Character ranges
[A-C][n-p][a-c]

Lesson 6: Catching some zzz's
wazz+up$

Lesson 7: Mr. Kleene, Mr. Kleene
(aa)+b{0,4}c+$

Lesson 8: Characters optional
\d{1,2} files? found\?

Lesson 9: All this whitespace
\d.\s+abc

Lesson 10: Starting and ending
^(Mission:) successful

Lesson 11: Match groups
(\w*).pdf$

Lesson 12: Nested groups
(\w{3} (\d{4}))

Lesson 13: More group work
(\d{4})x(\d{3,4})

Lesson 14: It's all conditional
I love (cats|dogs)

Lesson 15: Other special characters
The.*?\.$

进阶习题
Problem 1: Matching a decimal numbers
^-?\d+(,\d{3})*.?\de?\d*$

Problem 2: Matching phone numbers
1?\s?\(?(\d{3})[-\) ]?\d{3}[- ]?\d{4}

Problem 3: Matching emails
(.*?)(\+\w+)?@.+(.com)$

Problem 4: Matching HTML
<(\w+?)[\> ].*</\1>

Problem 5: Matching specific filenames
(.*?).(jpg|png|gif)$

Problem 6: Trimming whitespace from start and end of line
\s*(.*)

Problem 7: Extracting information from a log file
.*?.(\w+)\((.*?):(\d+)\)$

Problem 8: Parsing and extracting data from a URL
(.*?)://(.*?):?(\d+?)?/.*

浙公网安备 33010602011771号