Skip to content

Instantly share code, notes, and snippets.

@idavis
Created August 21, 2012 18:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save idavis/3418032 to your computer and use it in GitHub Desktop.
Save idavis/3418032 to your computer and use it in GitHub Desktop.
Ruby Style Regex Matching in Powershell
Matched!
user = idavis
repo = octopress
sha = 7e548dec97365691571d3b6e3c880717129692b9
caption = haml.rb
file = haml.rb
link = https://github.com/idavis/octopress/blob/master/plugins/haml.rb
linkTitle = Current Version
function =~ {
param([regex]$regex, [switch]$debug, [switch]$caseSensitive)
process {
$matches = $null
$mached = $false
if($caseSensitive) {
$matched = $_ -cmatch $regex
} else {
$matched = $_ -match $regex
}
if(!$matched) { return $false }
foreach( $key in $matches.keys) {
if((![char]::IsDigit("$key")) -or ("$key" -eq "0")) {
continue
}
$name = "$key"
$value = $matches[$key]
$variableIsDeclared = @(Get-Variable $name -Scope 1 -ErrorAction SilentlyContinue).Length -gt 0
if($variableisDeclared) {
if($debug){
write-host "setting $name to $value"
}
Set-Variable -Name $name -Value $value -Scope 1
} else {
if($debug) {
write-host "making $name to $value"
}
New-Variable -Name $name -Value $value -Scope 1
}
}
return $true
}
}
$pattern = "^(\w+)\s+(\w+)\s+(\w+)\s*(\.?\w+.?\w*)?\s*(http[s]*:\/\/\S+)?\s*(\S[\S\s]*)?$"
$text = "idavis octopress 7e548dec97365691571d3b6e3c880717129692b9 haml.rb https://github.com/idavis/octopress/blob/master/plugins/haml.rb Current Version "
if($text | =~ $pattern) {
Write-Host "Matched!"
write-host "user = $1"
write-host "repo = $2"
write-host "sha = $3"
write-host "caption = $4"
write-host "file = $caption"
write-host "link = $5"
write-host "linkTitle = $6"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment