Match Everything Until And Everything After With Regex Lookaheads And Lookbehind

Pavol Kutaj
1 min readJul 29, 2021

The aim of this reference📚 is to provide a reference for PowerShell’s regex lookarounds, i.e.:

  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

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com