Search code examples
regexpowershellglobalmultiline

Powershell regex replace : string is unchanged


I'm trying to regex replace some groups of charactes in powershell using the following pattern:

/^(thedir[ ]=[ ]")(.)(:[/\])([a-zA-Z0-9])([/\]?.)$/gm

by using this instruction:

$fileContent = Get-Content $fileToProcess -Raw 
$fileContent -replace '(?m)^(thedir[ ]*=[ ]*")(.)(:[\/\\])([a-zA-Z0-9]*)([\/\\]?.*)$', '$1Z$3Here$5'
Write-Host "New file content is $fileContent"

but it fails doing anything at execution : $fileContent remains unchanged. I note that the /gm flags are important, and are missing in my instruction, but I don't find how to set them. I've tried to prefix the regex with (?m) without success (and also tried (?smi), why not :)):

$fileContent -replace '(?m)^(thedir[ ]*=[ ]*")(.)(:[\/\\])([a-zA-Z0-9]*)([\/\\]?.*)$', '$1Z$3Here$5'

As an example, let's process a my.ini containing:

[mysqld]
#skip-innodb

# The TCP/IP Port the MySQL Server will listen on
port=3306
max_allowed_packet=16M


#Path to installation directory. All paths are usually resolved relative to this.
#basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
basedir="C:/MySQL/"

#Path to the database root
#datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
datadir="C:/MySQLData/"

# The default character set that will be used when a new schema or table is
# created and no character set is defined
default-character-set=utf8

and replacing thedir in the matching string by basedir

For expected result see here

As for now, I don't have any change in the $fileContent using the previsouly mentionned instructions.

Can you help me to make this work?


Solution

  • As mentioned in the comments, the pattern works perfectly fine against the sample values in the linked regex101 test suite:

    enter image description here

    Beware that -replace doesn't have side-effects - it doesn't modify the left-hand side variable in-place (like perl's =~ for example).

    To store the resulting string(s), remember to re-assign them to a new or existing variable:

    $newFileContents = $fileContents -replace '(?m)^(thedir[ ]*=[ ]*")(.)(:[\/\\])([a-zA-Z0-9]*)([\/\\]?.*)$', '$1Z$3Here$5'
    Write-Host "New file contents is:`n$($newFileContents -join "`n")"