I'm new to Powershell and I wonder if there is any way to parse input from a string according to a format, just like the sscanf() function in PHP?
-
1As far as I know, there is no such a thing in PowerShell. But for a particular task a solution can be found anyway, otherwise such a thing would exist. For example, regular expressions are often used in PowerShell for simple and effective parsing.Roman Kuzmin– Roman Kuzmin2012-10-27 08:10:08 +00:00Commented Oct 27, 2012 at 8:10
-
It's sad to hear so but thanks for the information though. I will use regular expressions instead!Teiv– Teiv2012-10-27 13:25:12 +00:00Commented Oct 27, 2012 at 13:25
Add a comment
|
1 Answer
The PHP sscanf can be emulated with matching the input with a regex. As per the PHP manual page example, let's parse author data into XML like so,
$auth = "24`tLewis Carroll" # ` is the escape char in PSh
$mc = [regex]::Match($auth, "(\d+)\t(\w+)\s(\w+)")
write-host $("<author id='{0}'>`n <firstname>{1}</firstname>`n <surname>{2}</surname>`n</author>" -f $mc.Groups[1].Value, $mc.Groups[2].Value, $mc.Groups[3].Value)
Output
<author id='24'>
<firstname>Lewis</firstname>
<surname>Carroll</surname>
</author>