`

RegEx之loodahead与lookbehind

阅读更多
首先说明:

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

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

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


一、Lookahead

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

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



向前不匹配:(?!regEx)
> (regexp-match-positions #rx"grey(?!hound)"
    "the gray greyhound ate the grey socks")
'((27 . 31))

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





二、LookBehind


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

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


向后不匹配:(?<!regEx)
> (regexp-match-positions #rx"(?<!grey)hound"
    "the greyhound in the picture is not a hound")
'((38 . 43))

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





注意:

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






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








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
















-



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics