Search code examples
stringpowershellsubstring

String containing _ shorten to first and last character


I have file Text.txt containing:

sometext1 sometext2 sometext3 sometext4_sometext5_sometext6 sometext7 sometext8 sometext9_sometext10 sometext11

and i need only string containing _ shorten to first and last character, in powershell, to output:

sometext1 sometext2 sometext3 s4_s5_s6 sometext7 sometext8 s9_s0 sometext11

I'm a newbie in Powershell.

Thank you for your help.


Solution

  • Its a bit of a lengthy Regex, but I think it does what you need:

    (?<=[^])[^\s_]+(?=[^\s_]|[^]\s)|(?<=\s[^])[^\s]+(?=[^\s_]_)

    to be used like this:

    sometext1 sometext2 sometext3 sometext4_sometext5_sometext6 sometext7 sometext8 sometext9_sometext10 sometext11' -replace '(?<=_[^_])[^\s_]+(?=[^\s_]_|[^_]\s)|(?<=\s[^_])[^\s_]+(?=[^\s_]_)
    

    Here's the explanation of the Regex: https://regex101.com/r/aYVoa6/1