首页 > 代码库 > JQuery之正则表达式
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之正则表达式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。