正则表达式(字符串应用)

2020-04-24  本文已影响0人  jasmine_6aa1

正则表达式(regular expression):描述字符串匹配的模式(pattern),能实现非常复杂的文本查找替换操作。

1,为什么使用?

正则表达式用简短的代码,能实现非常复杂的文本查找替换操作;用字符串的api来实现同样的功能。

2,创建正则表达式的两种方式

// 方法一:
/匹配模式/。 如 /box/。

// 方法二:
new RegExp(匹配模式字符串)。 如 new RegExp('box')

区别:方法二支持传入变量

3,常见字符类型的匹配方式如下:

4,匹配的模式

注:不写g,那么默认为非全局匹配

g :全局匹配,即全局查找
i :对大小写不敏感的匹配
m : 多行匹配

5,正则表达式常见的方法

var  str = 'This is a text box, that is a check box.'
var reg = /box/;
var regG = /box/g;

1,匹配

/box/.test('This is a text box.') // 返回true
/box/.test('This is a text title.') // 返回 false
// 正则查询
str.search(regG) // 16 获取文本中第一个box首字母的索引值位置
str.search(reg) // 16 这里不管匹不匹配 `g`,返回结果都一样

// 字符串查询
str.search('box') // 16 获取文本中第一个box首字母的索引值位置

2,提取
1,RegExpObject.exec(string):方法用于检索字符串中的正则表达式的匹配;提取一个内容
string:必需;要检索的字符串;exec()只返回一个匹配的结果

exec() 方法 — 案例

// 只返回第一个匹配的数组
var content = reg.exec(str);// [{0: "box", groups: undefined, index: 15, input: "This is a text box, that is a check box", length: 1}]

// 全局搜索
// 想返回几个,就调用几次,如果没有了,返回值为 null,所以这里写一个循环比较方便
do {
    var content = regG.exec(str)
    if (content) {
        console.log(content[0])
    }
 } while (content)

2,stringObject.match(regexp/substr):在字符串内检索指定的值,或找到一个或多个正则表达式的匹配;返回值是一个数组,没查询到返回 null;提取多个内容
注:regexp/substr:必须,查找的正则表达式或者字符串

match() 方法 — 案例

// 正则表达式用法 — 对象
str.match(regG) ;//  ["box", "box"]
str.match(reg) ;// {0: "box", groups: undefined, index: 15, input: "This is a text box, that is a check box", length: 1}  默认返回第一个查询到值的对象
str.match(/boxs/);  // null

// 正则表达式用法 — 字符串
str.match(‘box’); // {0: "box", groups: undefined, index: 15, input: "This is a text box, that is a check box", length: 1}  默认返回第一个查询到值的对象

3,替换
stringObject.replace(regexp,replacement):在字符串中用一些字符替换替换一个与正则表达式匹配的子串;返回一个新的字符串

var str =' This is a text box, that is a check box.'

正则表达式:全局替换 与 非全局替换
str.replace(/box/g, 'button');//  " This is a text button, that is a check button."
str.replace(/box/, 'button');// " This is a text button, that is a check box."

字符串替换
str.replace('box', 'button');// " This is a text button, that is a check box."

4,切割
stringObject.split(substr,howmany):在字符串中用一些字符替换另一些字符;返回一个新的数组

// 字符串
str.split( ' ', 5); // ["This", "is", "a", "text", "box,"]
str.split( '', 5);  // ["T", "h", "i", "s", " "]

// 将分割结构更为复杂的字符串
"|a|b|c".split("|") //将返回["", "a", "b", "c"]

6,匹配文本以...开始和以...结尾

查找文本是否以字母开头,以数字结尾。代码实现如下:

/^[a-zA-Z].*\d$/.test('ab1') // true

^用来匹配输入字符串的开始位置。$用来匹配输入字符串的结束位置。

7,匹配重复

/aaaaa/.test('aaaaa') // true
/a{5}/.test('aaaaa') // true

/(138|159)/.test('138') // true
/(138|159)/.test('159') // true

重复字符的匹配方式如下:

8,贪婪模式与非贪婪模式

这里不做详细介绍

// 贪婪模式
/<.+>/

// 非贪婪模式,在贪婪模式后面加一个 ?
/<.+?>/
上一篇 下一篇

猜你喜欢

热点阅读