使用PowerShell 4.0从变量输入中删除空格 [英] Removing spaces from a variable input using PowerShell 4.0
问题描述
我已经尝试了一些方法,但是由于某些原因它们似乎没有起作用.
I've tried a few things already but they don't seem to work for some reason.
基本上我想做的是让用户使用 读取主机" cmdlet,然后将其删除任何空格.
Basically what I'm attempting to do is have a user input a value using the "Read-host" cmdlet, then strip it of any spaces.
我尝试过:
$answer = read-host
$answer.replace(' ' , '""')
并且:
$answer = read-host
$answer -replace (' ')
我可能会错过一些确实很明显的东西,但是如果有人可以帮助我或向我展示实现这一目标的更简单方法,我将不胜感激.
I'm probably missing something really obvious, but if anyone could help me out or show me an easier way to achieve this I would appreciate it.
我本来打算将变量通过管道传递给命令并以这种方式剥离它,但是我看过的所有示例都没有用,尽管它们看起来很简单.
I was going to pipeline the variable to a command and strip it in that fashion, but none of the examples I've seen work, although they look much easier.
推荐答案
Replace
运算符的意思是用其他东西代替;不要与删除功能混淆.
The Replace
operator means Replace something with something else; do not be confused with removal functionality.
此外,您还应该将运算符处理后的结果发送到变量或其他运算符. .Replace()
和-replace
都不会修改原始变量.
Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace()
, nor -replace
modifies the original variable.
要删除所有空格,请使用'用空字符串替换任何空格符号'
To remove all spaces, use 'Replace any space symbol with empty string'
$string = $string -replace '\s',''
要删除行首和末尾的所有空格,并将所有重复的空格或制表符替换为空格键,请使用
To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use
$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '
或更本地的System.String
方法
$string = $string.Trim()
最好使用
Regexp,因为' '
仅表示空格键"符号,而'\s'
表示空格键,制表符和其他空格符号".请注意,$string.Replace()
进行'Normal'替换,而$string -replace
进行RegEx替换,这更重但是功能更多.
Regexp is preferred, because ' '
means only 'spacebar' symbol, and '\s'
means 'spacebar, tab and other space symbols'. Note that $string.Replace()
does 'Normal' replace, and $string -replace
does RegEx replace, which is more heavy but more functional.
请注意,RegEx具有一些特殊符号,例如点(.
),花括号([]()
),斜杠(\
),帽子(^
),数学符号(+-
)或美元符号( $
)确实需要转义. ('my.space.com' -replace '\.','-'
=> 'my-space-com'
.必须小心在右侧使用带有数字(例如$1
)的美元符号
Note that RegEx have some special symbols like dot (.
), braces ([]()
), slashes (\
), hats (^
), mathematical signs (+-
) or dollar signs ($
) that need do be escaped. ( 'my.space.com' -replace '\.','-'
=> 'my-space-com'
. A dollar sign with a number (ex $1
) must be used on a right part with care
'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033
更新:您还可以将$str = $str.Trim()
以及TrimEnd()
和TrimStart()
一起使用.在 System.String 中了解更多信息MSDN页面.
UPDATE: You can also use $str = $str.Trim()
, along with TrimEnd()
and TrimStart()
. Read more at System.String MSDN page.
这篇关于使用PowerShell 4.0从变量输入中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!