用正则表达式替换不工作 - replace not working with regex

- 此内容更新于:2015-12-20
主题:

我想替换字符串由用户输入。我有以下输入(firstname、lastname)…我用下面的代码:输出如下:我需要输出看起来像这样:我做错了什么?

原文:

I'm trying to replace a string input by a user. I have the following input (as a firstname, lastname)...

John, Doe

I am use the following code:

$userInput = $userInput -replace '\s',''
$firstName = $userInput -replace ",*$",""
$lastName = $userInput -replace "^*,",""

Output looks like the following:

$userInput = John,Doe
$firstName = John,Doe
$lastName = JohnDoe

I need the output to look like this:

$userInput = John,Doe
$firstName = John
$lastName = Doe

What am I doing wrong?

网友:

(原文:$firstName, $lastName = $userInput -split ',\s*')

网友:它的工作原理,谢谢:)

(原文:it works, thanks :))

楼主:@FiddleFreak以来,我的回答我了,我在写类似的事情的时候,当然如果PetSerAl写答案随时接受。:)

(原文:@FiddleFreak I've included that in my answer since I was writing something similar, but of course if PetSerAl writes an answer feel free to accept that. :))

解决方案:
找到0或多个逗号表示字符串的结尾(不是你想要的)。是..我不确定它会被视为有效的正则表达式。我猜这意味着找到0或多个“字符串的开始”,后跟一个逗号(奇怪的指定)。对于名字,你会真的想要这样的:所以说,找到一个逗号,后跟0或多个任意字符结束的字符串(然后用什么取代它)。姓:这说,找到字符串的开始,紧随其后的是0或多个任意字符(贪婪,这是后意味着什么),然后用什么取代它。Aaaand我写这,@PetSerAl评论我最后的解决方案是什么,这是使用一个分裂:
原文:

,*$ says to find 0 or more commas at the very end of the string (not what you want).

^*, is.. well, I'm not really sure it would be considered valid regex. I guess it would mean find 0 or more "beginning of string" followed by a comma (it's a weird thing to specify).

So for first name, you would really want something like this:

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

So that says, find a comma followed by 0 or more of any character followed by the end of the string (then replace it with nothing).

For last name:

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

And this says, find the beginning of the string, followed by 0 or more of any character (non-greedy, that's what the ? after the * means), then replace it with nothing.

Aaaand as I'm writing this, @PetSerAl commented what my last solution was going to be, which is to use a split:

$firstName, $lastName = $userInput -split ',\s*'