RegEx之loodahead与lookbehind

[color=green][size=medium][b]首先说明:[/b][/size][/color]

1、哪边是前,哪边是后?
不像我们阅读一本书,排在前面的是前,排在后面的是后。
对于查找的游标(Cursor)来说,没有查找的是前,查找过的是后。

look-ahead :向未查找的字符串中查找。
look-behind :向已经查找过的字符串中查找。

2、loodahead 、lookbehind 出现之动机
为什么这么写呢?这牵涉到 Cursor 的移动问题。
这种操作并不移动 Cursor,不影响下一次查找。


[size=medium][b]一、Lookahead[/b][/size]

[b]向前匹配:(?=regEx)[/b]

> (regexp-match-positions #rx "grey(?=hound)"
"i left my grey socks at the greyhound")
'((28 . 32))

grey(?=hound): 该正则匹配 "grey",但是前面必须跟 "hound"。


[b]向前不匹配:(?!regEx)[/b]

> (regexp-match-positions #rx"grey(?!hound)"
"the gray greyhound ate the grey socks")
'((27 . 31))

grey(?!hound): 该正则匹配 "grey",但是前面不能是 "hound"。


[size=medium][b]二、LookBehind[/b][/size]


[b]向后匹配:(?<=regEx)[/b]

> (regexp-match-positions #rx"(?<=grey)hound"
"the hound in the picture is not a greyhound")
'((38 . 43))

(?<=grey)hound: 该正则匹配 "hound",但后面必须是"grey"


[b]向后不匹配:(?<!regEx)[/b]

> (regexp-match-positions #rx"(?<!grey)hound"
"the greyhound in the picture is not a hound")
'((38 . 43))

(?<!grey)hound: 该正则匹配 "hound",但后面不能是"grey"


[b]注意:[/b]

JavaScript 不支持 lookbehind:(?<= ) or (?<! ),但是支持 lookahead: (?= ) or (?! ).


引用:
https://docs.racket-lang.org/guide/Looking_Ahead_and_Behind.html


-
转载请注明
原文出处:http://lixh1986.iteye.com/blog/2324010


-
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值