Advertisement
NonplayerCharacter

Regex 101 | Look(behind|ahead)

Jun 28th, 2019
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. Examples
  2. Given the string foobarbarfoo:
  3.  
  4. bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
  5. bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
  6. (?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
  7. (?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
  8. You can also combine them:
  9.  
  10. (?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
  11.  
  12. Definitions
  13.  
  14. Look ahead positive (?=)
  15. Find expression A where expression B follows:
  16. A(?=B)
  17.  
  18. Look ahead negative (?!)
  19. Find expression A where expression B does not follow:
  20. A(?!B)
  21.  
  22. Look behind positive (?<=)
  23. Find expression A where expression B precedes:
  24. (?<=B)A
  25.  
  26. Look behind negative (?<!)
  27. Find expression A where expression B does not precede:
  28. (?<!B)A
  29.  
  30. Atomic groups (?>)
  31. An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
  32.  
  33. (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled
  34.  
  35. A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
  36.  
  37. (foo|foot)s applied to foots will:
  38. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
  39. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.
  40.  
  41. Some resources
  42. http://www.regular-expressions.info/lookaround.html
  43. http://www.rexegg.com/regex-lookarounds.html
  44.  
  45. SRC:
  46. https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement