Shortening Text

by Aug 11, 2015

Let's assume you want to chop off some text at the end of a string. This is the traditional approach using string operations:

$text = "Some text"
$fromRight = 3

$text.Substring(0, $text.Length - $fromRight)

A much more powerful way uses the -replace operator with regular expressions:

$text = "Some text"
$fromRight = 3

$text -replace ".{$fromRight}$"

This would take any character (".") that is $fromRight characters long and ends with the end of text ($).

Since regular expressions are really flexible, you could rewrite it to chop off digits only, and only a maximum of 4:

$text1 = "Some text with digits267686783"
$text2 = "Some text with digits3"

$text1 -replace "\d{0,5}$"
$text2 -replace "\d{0,5}$"

The quantifier "{0,5}" tells the regex engine that you want between 0 and 5 numbers, and the engine will take as much as it can get.

Twitter This Tip! ReTweet this Tip!