2012-08-27 213 views
2

我想分割一个字符串在power-shell中......我已经在字符串上做了一些工作,但我无法弄清楚这最后一部分。Powershell - 分割字符串

说我坐在这个字符串:

This is a string. Its a comment that's anywhere from 5 to 250 characters wide. 

我想它在30个字符标记分裂,但我不想拆分单词。如果我要拆分它,它会在下一行有一行“...... commen”......“那......”。

什么是分割字符串的优雅方式,50max,而不会把一个字分成两半?为了简单起见,一个词是一个空格(评论可能也有数字文本“$ 1.00”,不要把它分成两半)。

回答

7
$regex = [regex] "\b" 
$str = "This is a string. Its a comment that's anywhere from 5 to 250 characters wide." 
$split = $regex.split($str, 2, 30) 
+0

那么究竟是在做什么呢? –

+1

@DanielLoveJr - 代码使用'Regex.Split'的[this overload](http://msdn.microsoft.com/zh-cn/library/t0zfk0w1.aspx),以便将输入字符串拆分为最多两个在从第31个字符开始的第一个单词边界('\ b'正规表达式)上。 – Lee

0

不知道它有多优雅,但是一种方法是在30个字符长的子字符串中使用lastindexof来查找最大的子字符值。

$str = "This is a string. Its a comment that's anywhere from 5 to 250 characters wide." 
$thirtychars = $str.substring(0,30) 
$sen1 = $str.substring(0,$thirtychars.lastindexof(" ")+1) 
$sen2 = $str.substring($thirtychars.lastindexof(" ")) 
0

假设“字”是空格分隔的标记。

$str = "This is a string. Its a comment that's anywhere from 5 to 250 characters wide." 
$q = New-Object System.Collections.Generic.Queue[String] (,[string[]]$str.Split(" ")); 
$newstr = ""; while($newstr.length -lt 30){$newstr += $q.deQueue()+" "} 

令牌字符串(拆分空格),创建一个数组。使用构造函数中的数组创建队列对象,自动填充队列;那么,您只需将这些项目从队列中“弹出”,直到新字符串的长度尽可能接近极限。

请注意古怪的语法,[string[]]$str.Split(" ")以使构造函数正常工作。

mp