Skip to content

正则表达式与JavaScript

一、正则表达式基础知识

正则表达式在校验和格式化文本时经常能起到事半功倍的效果。

正则表达式里的特殊字符

字符

说明

\

用于切换字面量和特殊字符。比如,“w”表示字母“w”,“\w”则表示有特殊含义。又比如,“”则表示单纯的字符“$”而没有特殊含义。

^

匹配一段字符串的开头。

$

匹配一段字符串的结尾。

*

前面的匹配项出现0次或多次。

前面的匹配项出现1次或多次。

?

前面的匹配项出现0次或1次。

.

表示除了换行符(new line)以外的所有字符。

\b

单词边界。

\B

非单词边界。

\d

等同于[0-9],表示0~9之间的任意数字。

\D

任意非数字字符。

\f

Form feed

\n

换行(new line)。

\r

回车换行(carriage return)。

\s

等同于[ \f\n\r\t\v],匹配任意单个空白字符。

\S

匹配任意单个非空白字符。

\t

匹配Tab。

\v

Vertical tab

\w

等同于[a-zA-Z0-9_],匹配任意字母、数字、下划线。

\W

匹配任意非字母、非数字、非下划线的字符。

[abcde]

匹配中括号内字符集中的任意一个字符,如[abcde]匹配单个字符a或b或c或d或e。

[^abced]

匹配不包括在中括号内字符集中的字符。

[a-e]

匹配中括号内指定范围内的所有字符中的任意一个,如[a-e]表示字母a到字母e中的任意字母。

前面的匹配项出现n次。

前面的匹配项至少出现n次。

前面的匹配项出现n~m次。

()

将匹配项聚合起来,方便后面使用。

x|y

匹配x或y,比如(12)|(34)匹配“12”或者“34”。

正则表达式修饰符

Modifier

Meaning

g

单词global的意思,表示搜索所有可能的匹配项,而非找到第一个匹配项就停止寻找。

i

搜寻匹配项时不区分大小写。

二、正/负向肯/否定零宽断言

零宽断言,匹配的宽度为零。 (pattern):匹配pattern并捕获该匹配的子表达式,可以用$1~$9属性从匹配到的结果集合中检索对应的匹配。 (?:pattern):非捕获匹配。匹配pattern但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。 (?=pattern):正向肯定零宽断言。 (?!pattern):正向否定零宽断言。 (?<=pattern):负向肯定零宽断言。 (?<!pattern):负向否定零宽断言。

三、JS中的RegExp对象

JavaScript有个内置的RegExp对象。

RegExp对象的属性

属性

说明

$1 (最大到$9)

找寻被括号匹配的匹配想,$1表示第一个,$9表示第9个。

/(test)/.test('tesfd(test)232343') // 输出true
RegExp.$1 // 输出'test'

$_

Same as input

$*

Same as multiline

$&

Same as lastMatch

$+

Same as lastParen

$`

Same as leftContext

$'

Same as rightContext

constructor

Specifies that function that creates an object's prototype

global

Search globally (g modifier in use)

ignoreCase

Search case-insensitive (i modifier in use)

input

The string to search if no string is passed

lastIndex

The index at which to start the next match

lastMatch

The last matched characters

lastParen

The last parenthesized substring match

leftContext

The substring to the left of the most recent match

multiline

Whether strings are searched across multiple lines

prototype

Allows the addition of properties to all objects

rightContext

The substring to the right of the most recent match

source

The regular expression

RegExp对象的方法

方法

说明

compile(pattern, [, "g" | "i" | "gi"])

Compiles a regular expression

exec(string)

Executes a search for a match

test(string)

Tests for a match

toSource()

Returns a literal representing the object

soString()

Returns a string representing the specified object

valueOf()

Returns the primitive value of the specified object

四、字符串中一些可以用到正则的方法

字符串的一些可以用到正则的方法

方法

说明

match(re)

Finds a match for a regular expression pattern (re) within a string

replace(re,replaceStr)

Using the regular expression (re), performs the desired replacement

search(re)

Searches for a match to the regular expression (re)

split(re)

Splits a string based on a regular expression (re)

参考

天上的神明与星辰,人间的艺术和真纯,我们所敬畏和热爱的,莫过于此。