Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell: Replace underscores with either a period or @ sign

In PowerShell, I’m looking to convert a SharePoint Location string (john_smith_domain_com) to the proper addressing of john.Smith@domain.com.
I’m not sure which is the best way to go about doing this.
I know $var.Replace("_",".") would work to replace all the "_"s with "."s, but that doesn’t help the "@" going between the name and the domain.

Unfortunately, the domain isn’t always the same, or I’d be able to just .replace it easily.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine two -replace operations (this assumes a two-component domain name, such as domain.com):

# -> 'john.smith@domain.com'
'john_smith_domain_com' -replace '_(?![^_]+_[^_]+$)', '.' -replace '_', '@'
  • Regex _(?![^_]+_[^_]+$) matches all _ chars. except the second-to-last one.

  • After all these have been replaced with ., only the second-to-last one is left, which can then be replaced with @

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading