Teiv
Teiv

Reputation: 2635

Parses input from a string according to a format with Powershell?

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?

URL Refered

Upvotes: 1

Views: 1177

Answers (1)

vonPryz
vonPryz

Reputation: 24071

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>

Upvotes: 1

Related Questions