|
正则表达式(Regular Expressions)是用来处理文本和匹配模式的。很多语言都支持正则表达式,比如:perl,JAVA,JSCRIPT等等。
我们在某些文本编辑器进行查找替换时,其实也算是用了正则表达式。只是正则表达式的功能远不止此。先看看有哪些符号,匹配什么?
在JDK1.5的文档中,有这样的文字解释:
- Character classes
- [abc] a, b, or c (simple class)
- [^abc] Any character except a, b, or c (negation)
- [a-zA-Z] a through z or A through Z, inclusive (range)
- [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
- [a-z&&[def]] d, e, or f (intersection)
- [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
- [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)
- Predefined character classes
- . Any character (may or may not match line terminators)
- \d A digit: [0-9]
- \D A non-digit: [^0-9]
- \s A whitespace character: [ \t\n\x0B\f\r]
- \S A non-whitespace character: [^\s]
- \w A word character: [a-zA-Z_0-9]
- \W A non-word character: [^\w]
复制代码
不想翻译它,给点中文的。
- \w 字母或数字;相当于 [0-9A-Za-z]
- \W 非字母,数字
- \s [ \t\n\r\f]空字符;相当于 [ \t\n\r\f]
- \S 非空字符
- \d [0-9]数字;相当于 [0-9]
- \D 非数字字符
- * 前面元素出现0或多次
- + 前面元素出现1或多次
- {m,n} 前面元素最少出现m次,最多出现n次
- ? 前面元素最多出现1次;相当于 {0,1}
- $ 匹配输入字符串的结尾位置。
复制代码
这些也只是部分而已。先给个例子。
在网上填资料时,有时会遇到输入框只能输入数据或者只能输入英文的情况。好,就给个只能输入数字的例子。
只能输入数字:
<input type="text" onkeyup="value=value.replace(/\D/g,'')"> 或:
<input type="text" onkeyup="value=value.replace(/[^0-9]/g,'')">
有时候用来验证输入是否合法,比如E-mail地址验证。
- <script language="javascript">
- function emailCheck(strEmail)
- {
- var myReg = /^[_a-zA-Z0-9]+@([_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/;
- if(myReg.test(strEmail))
- alert("有效Email地址");
- else
- alert("无效Email地址");
- }
- </script>
- <form>
- <input type="text" name="mytext">
- <input type="button" value="OK" onsubmit="return false" onclick="emailCheck(mytext.value)">
- </form>
复制代码
还有日期验证,网址验证等,这里就不再给出例子了。在JAVA里要用到Pattern和Match类,也免了例子。
本文只是简单的介绍,有兴趣的话可以关注下正则表达式,大家一起学习交流。 |
|