Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

regex - Lookahead vs lookbehind

I have a hard time to understand the concepts of "lookahead" and "lookbehind". For example, there is a string "aaaaaxbbbbb". If we look at "x", does lookahead mean looking "x" towards "bbbbb" or "aaaaa"? I mean the direction.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the regex is x(?=insert_regex_here) that is a (positive) look*ahead*, which looks ahead, or forwards, in other words towards "bbbb". It means "find an x that is followed by insert_regex_here".

If the regex is (?<=insert_regex_here)x that is a (positive) look*behind*, which looks behind, or backwards, in other words towards "aaaa". It means "find an x that is preceded by insert_regex_here".

You can also have negative lookahead x(?!insert_regex_here) meaning "x not followed by insert_regex_here", and negative lookbehind (?<!insert_regex_here)x, meaning "x not preceded by insert_regex_here".

(The above (?= and (?<! etc are Perl regex syntax - the syntax might be slightly different depending on your flavour of regex).

I recommend you read the link that Chad gave in the comments. It has examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...