Created
August 21, 2012 18:14
-
-
Save idavis/3418032 to your computer and use it in GitHub Desktop.
Ruby Style Regex Matching in Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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