0

Writing string to a RichTextBox with the following code

$TextBox.text = "`r`n Some Text `r`n" + $TextBox.text

Under certain circumstances, I need to delete a specific line from the text. The problem, I manage to find and delete the line but the rest of the text moves only 1 line up instead of 2

$TextBox.text = (($TextBox.text -split "`n") | ? {$_ -notmatch 'WordToSearch'}) -join "`n"

As I said, it removes the line, but an unnecessary new line still remains. How can I remove it too without using array or other complicated way?

For example, this is how the text looks:

\\empty line
row 1, some text
\\empty line
row 2, some text
\\empty line

After my attempt of deleting row 1, it looks like this:

\\empty line
\\empty line
row 2, some text
\\empty line

Expected:

\\empty line
row 2, some text
\\empty line
1
  • If the first element in the Rich Text at [0] is the empty line, you could use a .Remove() method on it. Not sure off hand if RTB's are a collection or just one long array of strings Commented Apr 4, 2018 at 14:41

2 Answers 2

1

Here's one way to remove blank lines from a string:

$str = "Line 1`r`n`r`n`r`nLine 4`r`n`r`nLine 6"
while ( $str -match "`r`n`r`n" ) {
  $str = $str -replace "`r`n`r`n","`r`n"
}
$str
# now $str contains only "Line 1", "Line 4", and "Line 6"
Sign up to request clarification or add additional context in comments.

2 Comments

This is not the expected result. For the matter, I need to replace Line 6 with 4. rnrnrn there will be no such situation from the first place
My description did not claim to be the answer to your specific question but is a general solution.
0

You should be able to use -replace and then .trim() to ensure you don't end up with multiple blank lines (if the line to remove is the last one) then add your final blank line back in with +'`r`n'

$find = "row 1"
$TextBox.text = ($TextBox.text -replace "(?mi)^.*$find.*`$(`r?`n)*",'').trim()+'`r`n'

2 Comments

This method deletes all new lines
It removes them all then appends one back to ensure there is still a trailing one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.