2

I'm trying to split a string in power-shell... I've already done some work on the string, but i can't figure out this last part.

Say I'm sitting with this string:

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

I want to split it at the 30 character mark, but I don't want to split a word. If I was to split it, it would have "... commen" on one line... "t that..." on the next line.

What's a graceful way of splitting the string, 50max, without breaking a word in half? Say for simplicity sake a word is a space (comments might have numeric text "$1.00" in it as well. Don't want to split that in half either).

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

So what is this doing here exactly?
@DanielLoveJr - The code uses this overload of Regex.Split so it splits the input string into a maximum of two pieces on the first word boundary (the \b regex) starting from the 31st character.
0

Not sure how graceful it is, but one way to do it would be to use lastindexof on a substring 30 characters long to find your largest, sub 30 character value.

$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(" "))

Comments

0

Assuming that the "words" are tokens that are space delimited.

$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()+" "}

Tokenize the string (split on spaces), which creates an array. Creating the Queue object with the array in the constructor, automatically populates the queue; then, you just "pop" the items off the queue until the length of the new string is as close as it can get to the limit.

Note the quaint syntax ,[string[]]$str.Split(" ") to make the constructor work properly.

mp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.