Match Everything Until And Everything After With Regex Lookaheads And Lookbehind

  1. lookahead
  2. lookbehind

1. regex: lookaheads and lookbehinds

  • concepts to define patterns that only match they they
  • are / are not followed by a certain pattern → lookahead (positive / negative)
  • are / are not preceded by a certain pattern → lookbehind (positive / negative)
name       | pattern
-----------|-------------------------------------
lookahead | MATCH_PATTERN(?=LOOKAHEAD_PATTERN)
lookbehind | (?<=LOOKBEHIND_MATTERN)MATCH_PATTERN

2. example: lookbehind with the lookup of a bucket from the HashiCorp Consul CV

  • if I want to capture name that is after mr + an empty string (whitespace \s)
  • i need to use lookbehind syntax
[regex]::matches(‘mr paul’,’(?<=mr\s).*’).value
→→→ paul
  • I am getting the URL of the s3 bucket that is preceded by aws_setup_prod1/output/s3_bucket_kinesis_s3_enriched_id: with Hashicorp Consul in this way (and copy to clipboard for efficiency)

$regex = "(?<=aws_setup_prod1/output/s3_bucket_kinesis_s3_enriched_id:).*"
$returnedString = consul kv get -recurse customer/$consulName |
Select-String -pattern $regex
$streamingBucket = $returnedString.matches.value
$streamingBucket | clip
write-host $streamingBucket pasted to clipboard -foregroundcolor cyan

--

--

--

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

[iOS] Project: Expense Tracker. Part 2. Google Firebase

[iOS]Expense Tracker. Part 1. UI design

Adding Firebase to iOS Project — The Lazy Way

The Google app on iOS is increasingly like a web browser

The Google app on iOS is increasingly like a web browser

Dynamically Change the iOS App Icon in Xamarin.Forms

iOS: Integrate Firebase Crashlytics properly

Building a UIKit user interface programmatically. Tips & suggestions.

Using tuist for building a workspace

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

10 useful String Operations in Python

Python Tips: How to write Pythonic Code

Tutorial 2 : OOPs in Python — more examples of objects and classes

Python object-oriented programming — Composition over Inheritance