JS 正则详解
test - 判断字符串是否符合规定的正则
rep =/\d+/;
rep.test('211')#true
rep =/^\d+$/
rep.test('2222ff3') #false
rep.test('22223') #true
exec -获取匹配的数据
req = /\d+/
str="wamhsjem_67_houyufa_21"
req.exec(str)#["67", index: 9, input: "wamhsjem_67_houyufa_21", groups: undefined]
var text = "JavaScript is more fun than Java or JavaBeans!";
var pattern = /\bJava\w*\b/;
result = pattern.exec(text)#["JavaScript"]
var pattern = /\bJava(\w*)\b/;#加分组
var pattern = /\bJava\w*\b/;#["JavaScript", "Script"]
var pattern = /\b(Java)\w*\b/g;#全局匹配
pattern.exec(text)#第一次拿["JavaScript"],第二次["Java"],第三次["JavaBeans"],第四次是null
1、定义正则表达式
/.../ 用于定义正则表达式
/.../g 表示全局匹配
/.../i 表示不区分大小写
/.../m 表示多行匹配
多行匹配例子:
var text = "JavaScript is more fun than \nJavaEE or JavaBeans!";
var pattern = /^Java\w*/g
pattern.exec(text)#["JavaScript"]
pattern.exec(text)#null
var pattern = /^Java\w*/gm;
pattern.exec(text)#第一次匹配["JavaScript"],第二次匹配["JavaEE"],第三次为null
var
pattern = /\bJava\w*\b/;
var
text =
"JavaScript is more fun than Java or JavaBeans!"
;
result = pattern.exec(text)