PowerShell: 用句点或@符号替换下划线

huangapple go评论74阅读模式
英文:

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):

# -&gt; &#39;john.smith@domain.com&#39;
&#39;john_smith_domain_com&#39; -replace &#39;_(?![^_]+_[^_]+$)&#39;, &#39;.&#39; -replace &#39;_&#39;, &#39;@&#39;
  • 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 &lt;firstName&gt;.&lt;lastName&gt; (as governed by a policy), you can replace the second _ with @:
# -&gt; &#39;john.smith@domain.co.uk&#39;
&#39;john_smith_domain_co_uk&#39; -replace &#39;^([^_]+)_([^_]+)_&#39;, &#39;$1.$2@&#39; -replace &#39;_&#39;, &#39;.&#39;
  • 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.

huangapple
  • 本文由 发表于 2023年2月7日 03:06:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定