js正则表达式

2016-11-24  本文已影响0人  angelwgh

正则表达式中的特殊字符

'^'号

/^A/.test("an A");   // true
/^A/.test("An E");   // false

'$'号

/t$/.test("eater");   // false
/t$/.test("eat");     // true

'*'号

"A ghost boooooed".replace(/bo*/,"c"); // "A ghost ced"

'+'号

'?'号

/e?le?/.exec("angel");        // ['el']
/e?le?/.exec("angle");        // ['le']
/e?le?/.exec("oslo");         // ['l']

/\d+?/.exec("123abc")         // ['1'] 非贪婪模式 (匹配尽量少的字符) 

'.'小数点

'(x)'圆括号 捕获括号

\n(n为正整数)表示第n个捕获括号中的内容

/(foo) (bar) \1 \2/.exec( "foo bar foo bar"); // ["foo bar foo bar", "foo", "bar"]

(?:x) 非捕获括号

/foo{1,2}/.exec("fooofooo");          //["fooo"]
/(?:foo){1,2}/.exec("foofooo");       //["foofoo"]  

x(?=y) 正向肯定查找

/Jack(?=Sprat)/.exec("JackSprat");        // ["Jack"]
/Jack(?=Sprat|Frost)/.exec("JackFrost")   // ["Jack"]

x(?!y) 正向否定查找

/\d+(?!\\.)/.exec("3.141")    // '141'

x|y

{n}

{n,m}

[xyz]

[^xyz]

\b

\B

\d

\D

\s

\S

\w

\W

正则表达式方法

exec()

regexObj.exec(str)
var re = /quick\s(brown).+?(jumps)/ig;
var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');

result{
    0: "Quick Brown Fox Jumps",
    1: "Brown",
    2: "Jumps",
    index: 4,
    input: "The Quick Brown Fox Jumps Over The Lazy Dog",
    length: 3
}

re{
    global: true,
    ignoreCase: true,
    lastIndex: 25,
    multiline: false,
    source: "quick\s(brown).+?(jumps)"
}

test()

regexObj.test(str)

执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 true 或 false。

上一篇 下一篇

猜你喜欢

热点阅读