Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created July 30, 2024 18:22
Show Gist options
  • Save IISResetMe/a488e952026abefddb40bc8f3c2ad2fc to your computer and use it in GitHub Desktop.
Save IISResetMe/a488e952026abefddb40bc8f3c2ad2fc to your computer and use it in GitHub Desktop.
StringBase.class.ps1 - string-parsing base class example
class StringBase {
hidden static [string] $_pattern = '(?!)'
hidden [string] $_value
# define single ctor with input string as its only parameter
StringBase([string]$value) {
$this._value = $value
if (-not $this.TryParse()) {
throw [ArgumentException]::new("Failed to parse input string '$value'", 'value')
}
}
# define parsing routine
hidden [bool]
TryParse() {
# use runtime type to discover (non-hidden) properties on derived types
$targetProperties = $this.GetType().GetProperties() |Where-Object { -not $_.GetCustomAttributes([System.Management.Automation.HiddenAttribute]) } |ForEach-Object Name
# construct pattern from static property on derived type
$pattern = [regex]::new($this::_pattern)
if (($match = $pattern.Match($this._value)).Success) {
# success, let's map group captures to class properties
$match.Groups |Where-Object { $_.Name -in $targetProperties -and $_.Success } |ForEach-Object {
$this.$($_.Name) = $_.Value
}
}
# indicate whether parsing succeeded
return $match.Success
}
}
<#
Example usage:
[ContactCard]'michael32 <[email protected]>'
#>
class ContactCard : StringBase {
hidden static [string] $_pattern = '^(?<Name>.*?)\s*<(?<Email>.*)>$'
[string]$Name
[string]$Email
ContactCard($value) : base($value) {}
}
<#
Example usage:
[LogMessage]"[$(Get-Date -f o)] INFO Hello there!"
#>
class LogMessage : StringBase {
hidden static [string] $_pattern = '^\[(?<When>.*?)\] (?<Severity>INFO|WARN|CRIT) (?<Message>.*)$'
[DateTime]$When
[string]$Severity
[string]$Message
LogMessage($value) : base($value) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment