2012-08-27 214 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