正则表达式入门(八)环视
环视是一种非捕获分组,它根据某个模式之前或之后的内容匹配其他模式。环视也称为零宽度断言。
环视包括:
- 正前瞻
- 反前瞻
- 正后顾
- 反后顾
THE RIME OF THE ANCYENT MARINERE, IN SEVEN PARTS. ARGUMENT. How a Ship having passed the Line was driven by Storms to the cold Country towards the South Pole; and how from thence she made her course to the tropical Latitude of the Great Pacific Ocean; and of the strange things that befell; and in what manner the Ancyent Marinere came back to his own Country. I. 1 It is an ancyent Marinere, 2 And he stoppeth one of three: 3 "By thy long grey beard and thy glittering eye 4 "Now wherefore stoppest me?
正前瞻
假设要匹配单词ancyent,且要求紧跟的单词是marinere,可以使用正前瞻。
(?i)ancyent(?=marinere)
(?i)不区分大小写,所以现在就是在每一行中寻找后跟marinere的单词ancyent。
反前瞻
反前瞻是正前瞻的取反操作。说明要在需要匹配的模式后找不到给定的前瞻内容。
(?i)ancyent(?!marinere)
这里,正前瞻的=变成了反前瞻的!。
正后顾
正后顾会查看前面的内容,和正前瞻的方向相反。
(?i)(?<=ancyent)marinere
反后顾
(?i)(?<!ancyent)marinere