JQuery之正则表达式
Posted Alex0425
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JQuery之正则表达式相关的知识,希望对你有一定的参考价值。
1.定义正则表达式
- /.../ 用于定义正则表达式
- /.../g 表示全局匹配
- /.../i 表示不区分大小写
- /.../m 表示多行匹配
2.匹配正则表达式
非全局模式,不分组
var pattern = /^Java\w*/m; var text = "javascript is more fun than JavaEE or JavaBeans!"; pattern.exec(text) pattern.exec(text) pattern.exec(text)
执行结果:
["JavaScript"] ["JavaScript"] ["JavaScript"]
非全局模式,分组
var pattern = /^Java(\w*)/m; var text = "JavaScript is more fun than \nJavaEE or JavaBeans!"; pattern.exec(text) pattern.exec(text) pattern.exec(text)
执行结果:
["JavaScript", "Script"] ["JavaScript", "Script"] ["JavaScript", "Script"]
全局模式,不分组
var pattern = /^Java\w*/gm var text = "JavaScript is more fun than JavaEE or JavaBeans!"; pattern.exec(text) pattern.exec(text) pattern.exec(text) pattern.exec(text)
执行结果:
["JavaScript"] null ["JavaScript"] null
全局模式,分组
var pattern = /^Java(\w*)/gm; var text = "JavaScript is more fun than JavaEE or JavaBeans!"; pattern.exec(text) pattern.exec(text) pattern.exec(text) pattern.exec(text) 执行结果:
["JavaScript", "Script"] null ["JavaScript", "Script"] null
3.
obj.search(regexp) 获取索引位置,搜索整个字符串,返回匹配成功的第一个位置(g模式无效)
obj.match(regexp) 获取匹配内容,搜索整个字符串,获取找到第一个匹配内容,如果正则是g模式找到全部
obj.replace(regexp, replacement) 替换匹配替换,正则中有g则替换所有,否则只替换第一个匹配项,
$数字:匹配的第n个组内容;
$&:当前匹配的内容;
$`:位于匹配子串左侧的文本;
$‘:位于匹配子串右侧的文本
$$:直接量$符号
var text = "JavaScript is more fun than \nJavaEE or JavaBeans!"; text.match(/Java\w+/mg);
["JavaScript", "JavaEE", "JavaBeans"]
var text = "JavaScript is more fun than \nJavaEE or JavaBeans!"; text.replace(/Java\w+/mg,‘Python‘);
"Python is more fun than
Python or Python!"
var text = "JavaScript is 8 more fun than 7 JavaEE or 6 JavaBeans!"; text.replace(/\d+/gm,‘Python‘);
"JavaScript is Python more fun than Python JavaEE or Python JavaBeans!"
var text = "JavaScript is 8 more fun than 7 JavaEE or 6 JavaBeans!"; text.replace(/\d+/gm,‘Python$&‘);
"JavaScript is Python8 more fun than Python7 JavaEE or Python6 JavaBeans!"
var text = "JavaScript is more fun than JavaEE or JavaBeans!"; text.replace(/Java/,‘==Python==$\‘‘); "==Python==Script is more fun than JavaEE or JavaBeans!Script is more fun than JavaEE or JavaBeans!" text.replace(/Java/,‘==Python==$`‘); "==Python==Script is more fun than JavaEE or JavaBeans!"
以上是关于JQuery之正则表达式的主要内容,如果未能解决你的问题,请参考以下文章