正则表达式
1.什么是正则表达式?
正则表达式是由一个字符序列形成的搜索模式。
当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容。
正则表达式可以是一个简单的字符,或一个更复杂的模式。
正则表达式可用于所有文本搜索和文本替换的操作。
2.语法
/正则表达式主体/修饰符(可选)
var patt = /runoob/i
// /runoob/i 是一个正则表达式。
// runoob 是一个正则表达式主体 (用于检索)。
// i 是一个修饰符 (搜索不区分大小写)。
使用字符串方法
1.在 JavaScript 中,正则表达式通常用于两个字符串方法 : search() 和 replace()。
a)
search() 方法 用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置。
实例:
使用正则表达式搜索 “Runoob” 字符串,且不区分大小写:
var str = "Visit Runoob!";
var n = str.search(/Runoob/i);
运行结果:6
search 方法可使用字符串作为参数。字符串参数会转换为正则表达式
var str = "Visit Runoob!";
var n = str.search("Runoob");
b)
replace() 方法 用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
实例:
使用正则表达式且不区分大小写将字符串中的 Microsoft 替换为 Runoob :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="myFunction()">点我</button>
<p id="demo">请访问 Microsoft!</p>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/microsoft/i,"Runoob");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
运行结果:请访问 Runoob!
replace() 方法将接收字符串作为参数
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("Microsoft","Runoob");
正则表达式修饰符
i — 执行对大小写不敏感的匹配。
g—执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)
m—执行多行匹配。
正则表达式模式
1.方括号用于查找某个范围内的字符:
[abc] 查找方括号之间的任何字符。
[0-9] 查找任何从 0 至 9 的数字。
(x|y) 查找任何以 | 分隔的选项。
需要补充
2.元字符是拥有特殊含义的字符:
\d 查找数字。
\s 查找空白字符。
\b 匹配单词边界。
\uxxxx 查找以十六进制数 xxxx 规定的 Unicode 字符。
需要补充
使用RegExp对象
详述见下章
使用 test()
1.test() 方法是一个正则表达式方法。
2.test() 方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
或:
// var patt1=/e/;
// document.write(patt1.test("The best things in life are free"));
或:
// document.write(/e/.test("The best things in life are free"));
</script>
</body>
</html>
使用 exec()
1.exec() 方法是一个正则表达式方法。
2.exec() 方法用于检索字符串中的正则表达式的匹配。该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
或:
// var patt1=/e/;
// document.write(patt1.exec("The best things in life are free"));
或:
// document.write(/e/.exec("The best things in life are free"));
</script>
</body>
</html>