有一类应用,从外部读取文本数据, 在应用中做进一步处理:
适用场景:
– A file on disk, in which case the specification is called the file format 输入 文件有特定格式,程序需读取文件并从中抽取正确的内容
– Messages sent over a network, in which case the specification is a wire protocol 从网络上传输过来的消息,遵循特定的协议
– A command typed by the user on the console, in which case the specification is a command line interface 用户在命令行输入的指令,遵循 特定的格式
– A string stored in memory 内存中存储的字符串,也有格式需要
三种基本的正则操作:
语法
代码 | 说明 |
---|---|
. | 匹配除换行符以外的任意字符 |
\w | 匹配字母或数字或下划线或汉字 |
\s | 匹配任意的空白符 |
\d | 匹配数字 |
\b | 匹配单词的开始或结束 |
^ | 匹配字符串的开始(在集合字符里[^a]表示非(不匹配)的意思 |
$ | 匹配字符串的结束 |
代码/语法 | 说明 |
---|---|
* | 重复零次或更多次 |
+ | 重复一次或更多次 |
? | 重复零次或一次 |
{n} | 重复n次 |
{n,} | 重复n次或更多次 |
{n,m} | 重复n到m次 |
▪ . any single character
▪ \d any digit, same as [0-9]
▪ \s any whitespace character, including space, tab, newline
▪ \w any word character, including underscore, same as [a-zA-Z_0-9]
▪ \., \(, \), \*, \+, ... escapes an operator or special character so that it matches literally
代码/语法 | 说明 |
---|---|
\W | 匹配任意不是字母,数字,下划线,汉字的字符 |
\S | 匹配任意不是空白符的字符 |
\D | 匹配任意非数字的字符 |
\B | 匹配不是单词开头或结束的位置 |
[^x] | 匹配除了x以外的任意字符 |