Read a configuration file: Difference between revisions

Content added Content deleted
(→‎{{header|PowerShell}}: Using Switch -Regex)
(→‎Using Switch -Regex: Using regex \s)
Line 3,430: Line 3,430:
=== Using Switch -Regex ===
=== Using Switch -Regex ===
<lang PowerShell>
<lang PowerShell>
Function Houdini-Value ([String]$_Text) {
$__Aux = $_Text.Trim(" `t")
If ($__Aux.Length -eq 0) {
$__Aux = $true
} ElseIf ($__Aux.Contains(',')) {
$__Aux = $__Aux.Split(',') |
ForEach-Object {
If ($PSItem.Trim(" `t").Length -ne 0) {
$PSItem.Trim(" `t")
}
}
}
Return $__Aux
}

Function Read-ConfigurationFile {
Function Read-ConfigurationFile {
[CmdletBinding()]
[CmdletBinding()]
Line 3,463: Line 3,448:
)
)


Begin {
Function Houdini-Value ([String]$_Text) {
$__Aux = $_Text.Trim()
If ($__Aux.Length -eq 0) {
$__Aux = $true
} ElseIf ($__Aux.Contains(',')) {
$__Aux = $__Aux.Split(',') |
ForEach-Object {
If ($PSItem.Trim().Length -ne 0) {
$PSItem.Trim()
}
}
}
Return $__Aux
}
}
Process {
Process {
$__Configuration = [Ordered]@{}
$__Configuration = [Ordered]@{}
# Config equivalent pattern
# Config equivalent pattern
# Select-String -Pattern '^((\t| )*)([^\t;#= ]+)(.*)((\t| )*)$' -LiteralPath '.\filename.cfg'
# Select-String -Pattern '^\s*([^\s;#=]+).*\s*$' -LiteralPath '.\filename.cfg'
Switch -Regex -File $_LiteralPath {
Switch -Regex -File $_LiteralPath {


'^((\t| )*)[;#=]|^((\t| )*)$' {
'^(\s*)[;#=]|^(\s*)$' {
Write-Verbose -Message '↓← ← ← ← ← ← ← ← ← ← ignored'
Write-Verbose -Message "v$(' '*20)ignored"
Write-Verbose -Message $Matches[0]
Write-Verbose -Message $Matches[0]
Continue
Continue
Line 3,479: Line 3,481:
Write-Verbose -Message $Matches[0]
Write-Verbose -Message $Matches[0]
$__Name,$__Value = $Matches[1..2]
$__Name,$__Value = $Matches[1..2]
$__Configuration[$__Name.Trim(" `t")] = Houdini-Value($__Value)
$__Configuration[$__Name.Trim()] = Houdini-Value($__Value)
Continue
Continue
}
}


'^((\t| )*)([^\t;#= ]+)(.*)((\t| )*)$' {
'^\s*([^\s;#=]+)(.*)(\s*)$' {
Write-Verbose -Message '↓← ← ← ← ← ← ← ← ← ← space or tab pattern or only name'
Write-Verbose -Message '↓← ← ← ← ← ← ← ← ← ← space or tab pattern or only name'
Write-Verbose -Message $Matches[0]
Write-Verbose -Message $Matches[0]
$__Name,$__Value = $Matches[3..4]
$__Name,$__Value = $Matches[1..2]
$__Configuration[$__Name.Trim(" `t")] = Houdini-Value($__Value)
$__Configuration[$__Name.Trim()] = Houdini-Value($__Value)
Continue
Continue
}
}