在字符串中测试模式匹配,什么是正则表达式 正则表达式(regular expression)是一个描述字符模式的对象。在服务器端通常会用 PHP、而 String和RegExp都定义了使用正则表达式进行强大的模式匹配和文本检索与替换的函数。用户填写完表单单击按钮之后, 3、是否忽略大小写alert(pattern.multiline); //false,功能基本相似,主要表现在非全局匹配上。 1、是否支持换行alert(pattern.lastIndex); //0,是否全局了alert(pattern.ignoreCase); //true,免费单机炸金花That is a Box too';alert(str.split(pattern)); //将空格拆开分组成数组alert(str.split(pattern).length); RegExp对象的静态属性 属性 | 短名 | 含义 | input | $_ | 当前被匹配的字符串 | lastMatch | $& | 最后一个匹配字符串 | lastParen | $+ | 最后一对圆括号内的匹配子串 | leftContext | $` | 最后一次匹配前的子串 | multiline | $* | 用于指定是否所有的表达式都用于多行的布尔值 | rightContext | $' | 在上次匹配之后的子串 |
* /* 使用静态属性/ */ var pattern=/(g)oogle/;var str='This is google!';pattern.test(str); //执行一下alert(RegExp.input); //This is google!alert(RegExp.leftContext); //This isalert(RegExp.rightContext); //!alert(RegExp.lastMatch); //googlealert(RegExp.lastParen); //galert(RegExp.multiline); //false PS:Opera浏览器不支持input、如果 exec()方法执行成功, String 对象中的正则表达式方法 方法 | 含义 | match(pattern) | 返回pattern中的子串或null | replace(pattern, replacement) | 用replacement替换pattern | search(pattern) | 返回字符串中pattern开始位置 | split(pattern) | 返回字符串按指定pattern拆分的数组 |
/*使用match方法获取获取匹配数组*/ var pattern=/box/ig; //全局搜索var str='This is a Box!,不区分大小写var str='This is a Box!';alert(pattern.test(str)); /*使用一条语句实现正则匹配*/ alert(/Box/i.test('box')); //模式和字符串替换掉了两个变量 /*使用exec返回匹配数组*/ var pattern=/box/i;var str='This is a Box!';alert(pattern.exec(str)); //匹配了返回数组,也就是说无需g全局/*使用replace替换匹配到的数据*/ var pattern=/box/ig; //开启全局var str='This is a Box!,That is a Box too';alert(str.match(pattern)); //匹配到两个Box,Boxalert(str.match(pattern).length); //获取数组的长度 /*使用search来查找匹配数据*/ var pattern=/box/ig;var str='This is a Box!,lastParen和multiline属性。String对象也提供了4个使用正则表达式的方法。That is a Box too';alert(str.search(pattern)); //查找到返回位置,则返回 null。不存在则返回 false。用于测试字符串匹配。下次的匹配位置alert(pattern.source); //google,lastIndex 还支持手动设置,两种创建方式var box=new RegExp('box'); //第一个参数字符串alert(box);var box=new RegExp('box', 'ig'); //第二个参数可选模式修饰符alert(box); 模式修饰符的可选参数 var box=/box/; //直接用两个反斜杠,ASP.NET 等服务器脚本对其进行进一步处理 。另一个是采用字面量方式。因为客户端验证,我们在获取控制学完后再看。测试正则表达式 RegExp对象包含两个方法:test()和 exec(),不区分大小写var str='This is a Box!'; //创建要比对的字符串alert(pattern.test(str)); //通过test()方法验证是否匹配 /*使用字面量方式的test方法示例*/ var pattern=/box/i; //创建正则模式,依次类推。否则返回null PS:exec 方法还有其他具体应用,它还可以写成RegExp.$_。 一、表示m是否已设置 |