PowerShell Trim bug with String containing “< char>$< repeated>”?

前端 未结 1 458
孤街浪徒
孤街浪徒 2021-01-26 01:36

If I use the Trim() method on a string containing -char-$-repeated char-, e.g. \"BL$LA\" or \"LA$AB\", Trim() strips the repeated char aft

相关标签:
1条回答
  • 2021-01-26 02:22

    The Trim() method removes all characters in the given argument (the string is automatically cast to a character array) from beginning and end of the string object. Your second example only seems to be doing what you want, because the remainder of the string does not have any of the characters-to-be-trimmed in it.

    Demonstration:

    PS C:\> $a = 'BL$LA'
    PS C:\> $a.Trim("BL$")
    A
    PS C:\> $a = 'LxB$LA'
    PS C:\> $a.Trim("BL$")
    xB$LA
    

    To remove a given substring from beginning and end of a string you need something like this instead:

    $a -replace '^BL\$|BL\$$'
    

    Regular expression breakdown:

    • ^ matches the beginning of a string.
    • $ matches the end of a string.
    • BL\$ matches the literal character sequence "BL$".
    • ...|... is an alternation (match any of these (sub)expressions).

    If you just want to remove text up to and including the first $ from the beginning of a string you could also do something like this:

    $a -replace '^.*?\$'
    

    Regular expression breakdown:

    • ^ matches the beginning of a string.
    • \$ matches a literal $ character.
    • .*? matches all characters up to the next (sub)expression (shortest/non-greedy match).
    0 讨论(0)
提交回复
热议问题