正则表达式六:字符重复匹配
介绍
用来匹配零次、一次、多次等
元字符列表
- 一次及以上匹配:
+ - 零次及以上匹配:
* - 零次或一次匹配:
? - 确定次数匹配:
{n} - 次数范围匹配:
{n1,n2} - 最小次数匹配:
{n,} - 一次及以上匹配(懒惰模式):
+? - 零次及以上匹配(懒惰模式):
*? - 次数匹配(懒惰模式):
{n}?、{n1,n2}?、{n,}?
一次及以上匹配(+)
匹配一次或多次字符
示例
原始内容:
Send personal email to ben@forta.com or
ben.forta@forta.com. For questions about a
book use support@forta.com. If your message
is urgent try ben@urgent.forta.com. Feel
free to send unsolicited email to
spam@forta.com (wouldn't it be nice if
it were that simple, huh?).
正则表达式:
[\w.]+@[\w.]+\.\w+
Send personal email to
ben@forta.comor
ben.forta@forta.com. For questions about a
book usesupport@forta.com. If your message
is urgent tryben@urgent.forta.com. Feel
free to send unsolicited email to
spam@forta.com(wouldn't it be nice if
it were that simple, huh?).
说明:
[\w.]+代表匹配一次或多次字母数字字符或者字符.
\w+代表匹配一次或多次字母数字字符
零次及以上匹配(*)
匹配零次或多次字符
示例
原始内容:
Hello .ben@forta.com is my email address.
正则表达式:
\w+[\w.]*@[\w.]+\.\w+
Hello .
ben@forta.comis my email address.
说明:
\w+代表开头需要匹配一次或多次字母数字字符
[\w.]*代表匹配零次或多次字母数字字符或者字符.,本示例中代表匹配零次
零次或一次匹配(?)
匹配零次或一次字符
示例
原始内容:
The URL is http://www.forta.com/, to connect
securely use https://www.forta.com/ instead.
正则表达式:
https?:\/\/[\w.\/]+
The URL is
http://www.forta.com/, to connect
securely usehttps://www.forta.com/instead.
说明:
https?代表匹配http或者https
[\w.\/]+代表匹配一次或多次字母数字字符或者字符.或者字符/
确定次数匹配({n})
字符匹配固定的次数
示例
原始内容:
body {
background-color: #fefbd8;
}
h1 {
background-color: #0000ff;
}
div {
background-color: #d0f4e6;
}
span {
background-color: #f08970;
}
正则表达式:
#[A-Fa-f0-9]{6}
body {
background-color:#fefbd8;
}
h1 {
background-color:#0000ff;
}
div {
background-color:#d0f4e6;
}
span {
background-color:#f08970;
}
说明:
[A-Fa-f0-9]代表匹配单个十六进制字符
{6}代表重复六次匹配
次数范围匹配({n1,n2})
字符匹配指定范围的次数
示例
原始内容:
4/8/17
10-6-2018
2/2/2
01-01-01
正则表达式:
\d{1,2}[-\/]\d{1,2}[-\/]\d{2,4}
4/8/17
10-6-2018
2/2/2
01-01-01
说明:
\d{1,2}代表匹配一次或两次数字字符
[-\/]代表匹配字符-或者字符/
最小次数匹配({n,})
字符至少匹配一定的次数
示例
原始内容:
1001: $496.80
1002: $1290.69
1003: $26.43
1004: $613.42
1005: $7.61
1006: $414.90
1007: $25.00
正则表达式:
\d+: \$\d{3,}\.\d{2}
1001: $496.80
1002: $1290.69
1003: $26.43
1004: $613.42
1005: $7.61
1006: $414.90
1007: $25.00
说明:
\d+:代表匹配前置序号
\d{3,}代表至少匹配三次数字字符,其他未匹配项都因为未满足此要求
懒惰模式匹配(+?、*?、{n}?、{n1,n2}?、{n,}?)
为了防止过多匹配内容
示例
原始内容:
This offer is not available to customers
living in <b>AK</b> and <b>HI</b>.
正则表达式1:
<[Bb]>.*<\/[Bb]>
This offer is not available to customers
living in<b>AK</b> and <b>HI</b>.
说明:
.*为贪婪模式匹配,寻找最大可能字符的匹配结果
正则表达式2:
<[Bb]>.*?<\/[Bb]>
This offer is not available to customers
living in<b>AK</b>and<b>HI</b>.
说明:
.*?为懒惰模式匹配,寻找最小可能字符的匹配结果
浙公网安备 33010602011771号