Match Everything Until And Everything After With Regex Lookaheads And Lookbehind
1 min readJul 29, 2021
The aim of this reference📚 is to provide a reference for PowerShell’s regex lookarounds, i.e.:
- lookahead
- 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