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 @
As JohnLBevan notes, if there are domain names with a varying number of components, you have two options:
- If you can assume that all users names are in the form
<firstName>.<lastName>
(as governed by a policy), you can replace the second _
with @
:
# -> 'john.smith@domain.co.uk'
'john_smith_domain_co_uk' -replace '^([^_]+)_([^_]+)_', '$1.$2@' -replace '_', '.'
- Otherwise, as John notes:
You may want something that's aware of the more common TLDs / caters for more common domain formats. Some options are in this post.