/

javascript-string-match

match()方法的字串

深入了解JavaScript的字串match()方法

给定一个由regex标识的正则表达式,尝试在字串中匹配它。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'Hi Flavio'.match(/avio/)
// Array [ 'avio' ]

'Test 123123329'.match(/\d+/)
// Array [ "123123329" ]

'hey'.match(/(hey|ho)/)
//Array [ "hey", "hey" ]

'123s'.match(/^(\d{3})(\w+)$/)
//Array [ "123s", "123", "s" ]

'123456789'.match(/(\d)+/)
//Array [ "123456789", "9" ]

'123s'.match(/^(\d{3})(?:\s)(\w+)$/)
//null

'123 s'.match(/^(\d{3})(?:\s)(\w+)$/)
//Array [ "123 s", "123", "s" ]

'I saw a bear'.match(/\bbear/) //Array ["bear"]

'I saw a beard'.match(/\bbear/) //Array ["bear"]

'I saw a beard'.match(/\bbear\b/) //null

'cool\_bear'.match(/\bbear\b/) //null

要了解有关正则表达式的更多信息,请参阅我的正则表达式教程

tags: [“JavaScript”, “String”, “match() method”, “Regular Expressions”]