9/7 正则表达式思路总结

来源:互联网 发布:通信网络系统组成 编辑:程序博客网 时间:2024/06/01 21:51

基本概念Regular expressions 正则表达式被用来根据某种匹配模式来寻找strings中的某些单词。

举例:如果我们想要找到字符串The dog chased the cat中单词 the,我们可以使用下面的正则表达式:/the/gi

我们可以把这个正则表达式分成几段:

/ 是这个正则表达式的头部

the 是我们想要匹配(或者说寻找)的字符串

/ 是这个正则表达式的尾部

g 代表着global(全局),意味着返回所有的匹配而不仅仅是第一个。

i 代表着忽略大小写,意思是当我们寻找匹配的字符串的时候忽略掉字母的大小写。

代码举例:
var testString = "Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.";                  var expressionToGetSoftware = /software/gi;         var digitCount = testString.match(expression).length  ;                              

特殊选择器: 1)数字选择器\d。举例说明/\d+/g在选择器后面添加一个加号标记(+),例如:/\d+/g,它允许这个正则表达式匹配一个或更多数字。尾部的g是'global'的简写,意思是允许这个正则表达式 找到所有的匹配而不是仅仅找到第一个匹配。使得

// 初始化变量var testString = "There are 3 cats but 4 dogs.";// 请只修改这条注释以下的代码var expression = /\d+/g;  // 用 \d 选择器来选取字符串中的所有数字。// 用 digitCount 存储 testString 中匹配到 expression 的次数var digitCount = testString.match(expression).length;
2)空白字符选择器\s。 举例说明/\s+/g

var testString = "How many spaces are there in this sentence?";var expression = /\s+/g;  // 请修改这一行// 用 spaceCount 存储 testString 中匹配到 expression 的次数var spaceCount = testString.match(expression).length;
3)非空白字符选择器\S。大写版本 来转化任何匹配。

// 初始化变量var testString = "How many non-space characters are there in this sentence?";var expression = /\S/g;  // 用 nonSpaceCount 存储 testString 中匹配到 expression 的次数var nonSpaceCount = testString.match(expression).length;