Share via


PowerShell Tip: String Manipulation using Regular Expression

Summary

  • Regular Expression is very powerful and the best way to play with strings.
  • Using REGEX in PowerShell is the best way to query log files, pattern matching etc. However, we should use it as applicable.

Regular Expression

 help about_Regular_Expressions

Swapping Strings Using Regex

 #Given Name : Chendrayan Venkatesan

#Required Output: Venkatesan , Chendrayan

"Chendrayan Venkatesan" -replace "([a-z]+)\s([a-z]+)" ,'$2, $1'

Explanation: ([a-z]+) captures a-z characters in the string ans \s is for white space. $2 is result of second captured value [Venkatesan] and $1 is for the first value [Chendrayan]

Removing Digits from String

 #Given Name : Chendrayan12345 Venkatesan

#Required Output: Chendrayan Venkatesan

'Chendrayan12345 Venkatesan' -replace "\d+"

Enjoy PowerShell :)