Brace expansion: Difference between revisions

Added PowerShell
(→‎{{header|Ruby}}: easy to understand.)
(Added PowerShell)
Line 1,755:
{a,b{1e}f
{a,b{2e}f</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<lang PowerShell>
function Expand-Braces ( [string]$String )
{
$Escaped = $False
$Stack = New-Object System.Collections.Stack
$ClosedBraces = $BracesToParse = $Null
ForEach ( $i in 0..($String.Length-1) )
{
Switch ( $String[$i] )
{
'\' {
$Escaped = -not $Escaped
break
}
'{' {
If ( -not $Escaped ) { $Stack.Push( [pscustomobject]@{ Delimiters = @( $i ) } ) }
}
',' {
If ( -not $Escaped -and $Stack.Count ) { $Stack.Peek().Delimiters += $i }
}
'}' {
If ( -not $Escaped -and $Stack.Count )
{
$Stack.Peek().Delimiters += $i
$ClosedBraces = $Stack.Pop()
If ( $ClosedBraces.Delimiters.Count -gt 2 )
{
$BracesToParse = $ClosedBraces
}
}
}
default { $Escaped = $False }
}
}
If ( $BracesToParse )
{
$Start = $String.Substring( 0, $BracesToParse.Delimiters[0] )
$End = $String.Substring( $BracesToParse.Delimiters[-1] + 1 )
ForEach ( $i in 0..($BracesToParse.Delimiters.Count-2) )
{
$Option = $String.Substring( $BracesToParse.Delimiters[$i] + 1, $BracesToParse.Delimiters[$i+1] - $BracesToParse.Delimiters[$i] - 1 )
Expand-Braces ( $Start + $Option + $End )
}
}
Else
{
$String
}
}
</lang>
<lang PowerShell>
$TestStrings = @(
'It{{em,alic}iz,erat}e{d,}, please.'
'~/{Downloads,Pictures}/*.{jpg,gif,png}'
'{,{,gotta have{ ,\, again\, }}more }cowbell!'
'{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}'
)
ForEach ( $String in $TestStrings )
{
''
$String
'------'
Expand-Braces $String
}
</lang>
{{out}}
<pre>
It{{em,alic}iz,erat}e{d,}, please.
------
Itemized, please.
Italicized, please.
Iterated, please.
Itemize, please.
Italicize, please.
Iterate, please.
 
~/{Downloads,Pictures}/*.{jpg,gif,png}
------
~/Downloads/*.jpg
~/Pictures/*.jpg
~/Downloads/*.gif
~/Pictures/*.gif
~/Downloads/*.png
~/Pictures/*.png
 
{,{,gotta have{ ,\, again\, }}more }cowbell!
------
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
 
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
------
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Python}}==