Regular expressions 正则表达式
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 softwareCount = testString.match(expressionToGetSoftware).length;
var expression = /and/gi; // Change this Line
// This code counts the matches of expression in testString
var andCount = testString.match(expression).length;
在正则表达式中使用特殊选择器来选取特殊类型的值。
特殊选择器中的一种就是数字选择器\d
,意思是被用来获取一个字符串的数字。
在JavaScript中, 数字选择器类似于: /\d/g
。
在选择器后面添加一个加号标记(+
),例如:/\d+/g
,它允许这个正则表达式匹配一个或更多数字。
var testString = "There are 3 cats but 4 dogs.";
// Only change code below this line.
var expression = /\d+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var digitCount = testString.match(expression).length;
用正则表达式选择器 \s
来选择一个字符串中的空白。
空白字符有 " "
(空格符)、\r
(回车符)、\n
(换行符)、\t
(制表符) 和 \f
(换页符)。
空白正则表达式类似于:
/\s+/g
// Setup
var testString = "How many spaces are there in this sentence?";
// Only change code below this line.
var expression = /\s+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var spaceCount = testString.match(expression).length;
用正则表达式选择器的大写版本 来转化任何匹配。
举个例子:\s
匹配任何空白字符,\S
匹配任何非空白字符。
// Setup
var testString = "How many non-space characters are there in this sentence?";
// Only change code below this line.
var expression = /\S/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var nonSpaceCount = testString.match(expression).length;
posted on 2017-06-13 11:37 Willy_Jane 阅读(141) 评论(0) 编辑 收藏 举报