I need to verify MAC address in RAW format using RegEx and split it into an array of 6 values by 2 characters.
When I use following pattern, I get content of last iteration of capture group only:
PS C:\Windows\System32> "708BCDBC8A0D" -match "^([0-9a-z]{2}){6}$"
True
PS C:\Windows\System32> $Matches
Name Value
---- -----
1 0D
0 708BCDBC8A0D
PS C:\Windows\System32>
With what pattern can I caputere all the groups?
I need this result:
0 = 708BCDBC8A0D
1 = 70
2 = 8B
3 = CD
4 = BC
5 = 8A
6 = 0D
You can not capture multiple groups with single group definition. Avoid using RegEx when unnecessary as it takes lots of CPU. Valuable for millions of recrds.
For MACs you can use special PhysicalAddress
class:
[System.Net.NetworkInformation.PhysicalAddress]::Parse('708BCDBC8A0D')
For .Net 5 (Powershell Core I think based on it) there is TryParse
method added, but in .Net 4.5 there is no TryParse
method.
To check .Net framework powershell running use [System.Reflection.Assembly]::GetExecutingAssembly().ImageRuntimeVersion
'708BCDBC8A0D' -match "^$('([A-F0-9]{2})' * 6)$"; $Matches
'708BCDBC8A0D' -match '^([A-F0-9]{2})([A-F0-9]{2})([A-F0-9]{2})([A-F0-9]{2})([A-F0-9]{2})([A-F0-9]{2})$'; $Matches
'@(0..5) | ForEach-Object {'708BCDBC8A0D'.Substring($_ * 2, 2)}'
@(
[String]::new('708BCDBC8A0D'[0..1]),
[String]::new('708BCDBC8A0D'[2..3]),
[String]::new('708BCDBC8A0D'[4..5]),
[String]::new('708BCDBC8A0D'[6..7]),
[String]::new('708BCDBC8A0D'[8..9]),
[String]::new('708BCDBC8A0D'[10..11])
)