Replace last occurrence of character in string

powershell, regex, replace, special-characters, string

Solution

Using the following string to match:

(.*)[/](.*)

and the following to replace:

$1 $2

Explanation:

`(.*)` matches anything, any number of times (including zero). By wrapping it in parentheses, we make it available to be used again during the replace sequence, using the placeholder `$` followed by the element number (as an example, because this is the first element, `$1` will be the placeholder). When we use the relevant placeholder in the replace string, it will put all of the characters matched by this section of the regex into the resulting string. In this situation, the matched text will be `01/01/2014 blbalbalbalba blabla`

`[/]` is used to match the forward slash character.

`(.*)` again is used to match anything, any number of times, similar to the first instance. In this case, it will match `blabla`, making it available in the `$2` placeholder.

Basically, the first three elements work together to find a number of characters, followed by a forward slash, followed by another number of characters. Because the first "match everything" is greedy (that is, it will attempt to match as many character as possible), it will include all of the other forward slashes as well, up until the last. The reason that it stops short of the last forward slash is that including it would make the regex fail, as the `[/]` wouldn't be able to match anything any more.

Problem

I've got the following string : 01/01/2014 blbalbalbalba blabla/blabla I would like to replace the last slash with a space, and keep the first 2 slashes in the date. The closest thing I have come up with was this kind of thing : ``` PS E:\> [regex] $regex = '[a-z]' PS E:\> $regex.Replace('abcde', 'X', 3) XXXde ``` but I don't know how to start from the end of the line. Any help would be greatly appreciated. Editing my question to clarify : I just want to replace the last slash character with a space character, therefore : 01/01/2014 blbalbalbalba blabla/blabla becomes 01/01/2014 blbalbalbalba blabla blabla Knowing that the length of "blabla" varies from one line to the other and the slash character could be anywhere. Thanks :)

Original source

Related problems