英文:
PowerShell: Replace underscores with either a period or @ sign
问题
在PowerShell中,我想要将SharePoint位置字符串(john_smith_domain_com)转换为正确的格式:john.Smith@domain.com。我不确定最佳的方法是什么。
我知道$var.Replace("_", ".")
可以将所有的"_"替换为".",但这不会解决在名称和域之间的"@"的问题。
不幸的是,域名并不总是相同的,否则我可以轻松地进行替换。
英文:
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.
答案1
得分: 3
# -> 'john.smith@domain.com'
'john_smith_domain_com' -replace '_(?![^_]+_[^_]+$)', '.' -replace '_', '@'
# -> 'john.smith@domain.co.uk'
'john_smith_domain_co_uk' -replace '^([^_]+)_([^_]+)_', '$1.$2@' -replace '_', '.'
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@
.
英文:
<!-- language-all: sh -->
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.- For an explanation of the regex and the ability to interact with it, see this regex101.com page.
-
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论