1

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

2
  • 1
    As 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. Commented Oct 27, 2012 at 8:10
  • It's sad to hear so but thanks for the information though. I will use regular expressions instead! Commented Oct 27, 2012 at 13:25

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.