使用子表达式

(1)Subexpressions are enclosed between ( and ) characters. 

To demonstrate the use of subexpressions, let's revisit the previous example:

Text
Hello, my name is Ben Forta, and I am

the author of books on SQL, ColdFusion, WAP,

Windows  2000, and other subjects.

RegEx
( ){2,}

Result
 
Hello, my name is Ben Forta, and I am

the author of books on SQL, ColdFusion, WAP,

Windows  

2000, and other subjects.
(2)子表达式分组

Capture groups are numbered, starting at 1, and moving from left to right, by counting the number of open parentheses it takes to reach them. The special group number 0 always refers to the entire expression match. For example, consider the following string:

    one ((two) (three (four)))

This string creates the following matches:

    Group 0: one two three four
    Group 1: two three four
    Group 2: two
    Group 3: three four
    Group 4: four
 
 
(3)子表达式是可以嵌套使用的,例如:
 
Text
Pinging hog.forta.com [12.159.46.200]

with 32 bytes of data:

RegEx
(((/d{1,2})|(1/d{2})|(2[0-4]/d)|(25[0-5]))/.){3}((/d{1,2})|(1/d{2})|(2[0-4]/d)|(25[0-5]))

Result
 
Pinging hog.forta.com [12.159.46.200

]

with 32 bytes of data:
 
Analysis

The pattern obviously worked, but it does require explanation. What makes this pattern work is a series of nested subexpressions.

We'll start with (((/d{1,2})|(1/d{2})|(2[0-4]/d)|(25[0-5]))/.) , a set of four nested subexpressions. (/d{1,2}) matches any one- or two-digit

number or numbers 0 through 99 . (1/d{2}) matches any three-digit number starting with 1 (1 followed by any two digits), or numbers 100 through 199 .

(2[0-4]/d) matches numbers 200 through 249 . (25[0-5]) matches numbers 250 through 255 . Each of these subexpressions is enclosed

within another subexpression with an | between each (so that one of the four subexpressions has to match, not all).

After the range of numbers comes /. to match . , and then the entire series (all the number options plus /. )

is enclosed into yet another subexpression and repeated three times using {3} .

Finally, the range of numbers is repeated (this time without the trailing /. ) to match the final IP address number.

By restricting each of the four numbers to values between 0 and 255 , this pattern can indeed match valid IP addresses and

reject invalid addresses.

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值