The look-ahead is used to only match the string if something lies ahead or does not lie ahead of the current match. The trick is that the look-ahead does not consume parts of the string. A second match would also consider parts of string, where the previous look-ahead matched.
positive look-ahead
(truck|car)s(?=\s)
Do trucks like cars?
This will only match trucks because cars is not followed by a whitespace.
negative look-ahead
(truck|car)s(?!\s)
Do trucks like cars?
This will only match cars because it is not followed by a whitespace.
positive look-behind
(?<=\s)(truck|car)
Are cars scary?
This will only match the first car and not the car in s-car-y because a whitespace needs to be behind the match.
negative look-behind
(?<!\s)(truck|car)
Are cars scary?
This will match the second car in scary because an s is not a whitespace.
look-around
(?<=[\ss])(truck|car)(?=[sy])
Are cars scary?
This will match both ,,car’’ . whitespace or s on the left and s or y on the right.
(?<=[\ss])(truck|car)(?![sy])
Do cars like carpets ?
Now the car in carpets will match.
Friday, January 30, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment