Does A String Start Or End In A Certain Character?

Can you tell in PowerShell if a string ends in a specific character, or if it starts in one? Of course you can. Regex to the rescue!

It’s a pretty simple task, actually. Consider the following examples

'something\' -match '.+?\\$'
#returns true

'something' -match '.+?\\$'
#returns false

'\something' -match '^\\.+?'
#returns true

'something' -match '^\\.+?'
#returns false

In the first two examples, I’m checking to see if the string ends in a backslash. In the last two examples, I’m seeing if the string starts with one. The regex pattern being matched for the first two is .+?\$ . What’s that mean? Well, the first part .+? means “any character, and as many of them as it takes to get to the next part of the regex. The second part <strong>\</strong> means “a backslash” (because \ is the escape character, we’re basically escaping the escape character. The last part $ is the signal for the end of the line. Effectively what we have is “anything at all, where the last thing on the line is a backslash” which is exactly what we’re looking for. In the second two examples, I’ve just moved the <strong>\</strong> to the start of the line and started with ^ instead of ending with $ because ^ is the signal for the start of the line.

Now you can do things like this.

$dir = 'c:\temp'
if ($dir -notmatch '.+?\\$')
  {
    $dir += '\'
  }
$dir
#returns 'c:\temp\'

Here, I’m checking to see if the string ‘bears’ ends in a backslash, and if it doesn’t, I’m appending one.

Cool, right?

Written on December 28, 2016