powershellregex-replace

How Do I End My Powershell Regex Syntax Torture?


I want a Powershell regex replace command to convert strings such as these...

RedHerringFallacy
SunkenCostFallacy
FalseDilemmaLogic
AnyOtherCamelCapString

to...

Red_Herring_Fallacy
Sunken_Cost_Fallacy
False_Dilemma_Logic
Any_Other_Camel_Cap_String

Here are all my unsuccessful attempts:

1) The Lookbehind

$string = "FundRegions"
$modifiedString = $string -replace '(?<=[a-z])(?=[A-Z])', '_'  
$modifiedString

Gives me: F_u_n_d_R_e_g_i_o_n_s

2) Plain and Simple

$string = "FundRegions"
$modifiedString = $string -replace '([a-z])([A-Z])', '$1_$2'
$modifiedString

Gives me: F_un_dR_eg_io_ns

3) There's No Going Backticks

$string = "FundRegions"
$modifiedString = $string -replace '([a-z])([A-Z])', '`$1_`$2'
$modifiedString 

Gives me: `F_`u`n_`d`R_`e`g_`i`o_`ns

4) One Character at a Time

$string = "FundRegions"
function InsertUnderscores([string]$str) {
    $result = ""
    for ($i = 0; $i -lt $str.Length; $i++) {
        $result += $str[$i]
        if ($i -lt $str.Length - 1 -and $str[$i] -match '[a-z]' -and $str[$i+1] -match '[A-Z]') {
            $result += '_'
        }
    }
    return $result
}

$modifiedString = InsertUnderscores $string
$modifiedString

Gives me: F_u_n_d_R_e_g_i_o_n_s

Calgon, take me away! Please help. Thank you.


Solution

  • I'll take a shot at it, case sensitive replace. I delete the _ at the beginning after. Most of what you did would work with -creplace or -cmatch, except the backticks which have to be in double quotes.

    (echo RedHerringFallacy SunkenCostFallacy FalseDilemmaLogic,
      AnyOtherCamelCapString) -creplace '([A-Z])','_$1' -replace '^_'
    
    Red_Herring_Fallacy
    Sunken_Cost_Fallacy
    False_Dilemma_Logic
    Any_Other_Camel_Cap_String
    

    Or in one step with negative lookbehind for beginning of line:

    (echo RedHerringFallacy SunkenCostFallacy FalseDilemmaLogic,
      AnyOtherCamelCapString) -creplace '(?<!^)([A-Z])','_$1'