regex - 替换不适用于正则表达式

标签 regex powershell powershell-3.0

我正在尝试替换用户输入的字符串。我有以下输入(作为名字,姓氏)...

John, Doe

我正在使用以下代码:
$userInput = $userInput -replace '\s',''
$firstName = $userInput -replace ",*$",""
$lastName = $userInput -replace "^*,",""

输出如下所示:
$userInput = John,Doe
$firstName = John,Doe
$lastName = JohnDoe

我需要输出看起来像这样:
$userInput = John,Doe
$firstName = John
$lastName = Doe

我究竟做错了什么?

最佳答案

,*$表示在字符串的末尾找到0个或多个逗号(不是您想要的)。
^*,是..好吧,我不太确定它是否被视为有效的正则表达式。我猜这意味着找到0个或多个“字符串开头”,后跟一个逗号(这是很奇怪的事情)。

因此,对于名字,您真的想要这样的东西:

$firstName = $userInput -replace ',.*$',''

就是说,找到一个逗号,后跟0个或多个任何字符,后跟字符串的结尾(然后将其替换为空)。

姓氏:
$lastName = $userInput -replace '^.*?,',''

这就是说,找到字符串的开头,后跟0个或多个任何字符(非贪心,这就是?之后的*的意思),然后将其替换为空。

在我撰写本文时,@ PetSerAl评论了我的最后一个解决方案,即使用拆分:
$firstName, $lastName = $userInput -split ',\s*'

关于regex - 替换不适用于正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365924/

相关文章:

powershell - 尝试通过 PowerShell 脚本查找并终止进程

uwp - 使用Powershell启动Metro风格的应用程序

powershell - 按州和姓名找工作?

python - 如何以这种方式打印字符串

python - 在正则表达式中转义美元符号不起作用

python - 如何在 python 中以不同的顺序正则表达式搜索字符串

python - Fabric 中的正则表达式和 sed 出现问题

powershell - 新的 Azure 资源组 powershell

string - 如何删除此字符串的左侧?

Powershell - 监控文件夹内容