A5下载文章资讯

分类分类

PowerShell String对象方法小结

2015-07-08 16:43作者:zhao

从之前的章节中,我们知道PowerShell将一切存储在对象中,那这些对象中包含了一系列中的称之为方法的指令。默认文本存储在String对象中,它包含了许多非常有用的处理文本的命令。例如,要确定一个文件的扩展名,可以使用LastIndexOf()获取最后一个字符“.”的位置,继续使用Substring()获取扩展名子串。

PS> $path = "C:prefs.js"

PS> $path.Substring( $path.LastIndexOf(".")+1 )

Js

另外一条途径,使用Split方法,对文件的完整名称进行分割,得到一个字符串数组,取最后一个元素,PowerShell中可以通过索引-1来获取数组中最后一个元素。

PS> $path.Split(".")[-1]

Js

下面的表格会给出String对象的所有方法:

以Split()为例来分析方法

在之前的章节中,我们已经知道可以通过Get-Member来查看一个对象中包含了那些可以被调用的方法。正好最为一个简单的回顾,来查看Split的定义。

PS C:> ("jb51.net" | Get-Member Split).definition

string[] Split(Params char[] separator), string[] Split(char[] separator, int count), string[] Split(char[] separator, System.StringSplitOptions options), string[] Split(char[] separator, int count, System.StringSplitOptions options), string[] Split(string[] separator, System.StringSplitOptions options), string[] Split(string[] sepa

rator, int count, System.StringSplitOptions options)

Define属性可以获取方法参数定义,但是可读性比较坑爹。我们仍然用上面表格中的Replace方法,将分隔符稍作替换,即可增强可读性。

PS C:> ("jb51.net" | Get-Member Split).definition.Replace("), ", ")`n")

string[] Split(Params char[] separator)

string[] Split(char[] separator, int count)

string[] Split(char[] separator, System.StringSplitOptions options)

string[] Split(char[] separator, int count, System.StringSplitOptions options)

string[] Split(string[] separator, System.StringSplitOptions options)

string[] Split(string[] separator, int count, System.StringSplitOptions options)

之前说过反引号,类似高级语言中的转义符反斜杠。

从上面的输出可以发现Split有6种不同的调用方法,而之前可能更多的只使用过一个参数的方法。PowerShell在处理文本时,可能会碰到多个分隔符,而Split方法调用只须一次即可。

PS C:> "http://down.admin5.com/info".split(":./")

http

www

pstips

net

中间有空白,咋整,能移除吗,StringSplitOptions轻装上阵:

PS C:> "http://down.admin5.com/info".split(":./",[StringSplitOptions]::RemoveEmptyEntries)

http

www

pstips

net

之前有一个小算法题,移除字符串中相邻的重复的空格。在不考虑效率的前提下,可以使用Split先分割,分割后再将得到的元素以指定分隔符拼接。但是拼接用到的Join方法,并不属于string对象,而属于String类,也正是下面要讲的。

 

展开全部

相关

说两句网友评论
    我要跟贴
    取消