I have a text file; within the file I have some square brackets that may include a comma. I want to replace/remove this comma. Say the text =
##logissue type=warning;Column 'Employee'[Address, Post]. Do not use floating point data types"
What I want is:
##logissue type=warning;Column 'Employee'[Address Post]. Do not use floating point data types"
I am using this PowerShell script, but this one replacing everything within the bracket squares.
$string -replace '\[.*\]', ''
CodePudding user response:
You can capture everything inside the square brackets and do the replacement with the help of a script block.
Within the script block you can use the $_
automatic variable to access the input text being replaced. Also note that this variable class type is System.Text.RegularExpressions.Match
, Hence you need to use .Value
to gets the captured substring.
$string -replace "\[(.*?)\]", { $_.Value.replace(",", "") }
Please note that this is available In PowerShell 6 and later.
For older versions you can use the Replace
function from
.NET regex
class.
[regex]::Replace($string, "\[(.*?)\]", { $args[0].Value.replace(',', "") })
CodePudding user response:
Powershell supports infinite quantifiers in a lookbehind assertion and you can assert [
to the left and ]
to the right while matching a comma.
(?<=\[[^][]*),(?=[^][]*])
Explanation
(?<=\[[^][]*)
Assert[
to the left matching any char except[
and]
in between,
Match the comma(?=[^][]*])
Assert]
to the right matching any char except[
and]
in between
$string = "##logissue type=warning;Column 'Employee'[Address, Post]. Do not use floating point data types"
$string -replace '(?<=\[[^][]*),(?=[^][]*])', ''
Output
##logissue type=warning;Column 'Employee'[Address Post]. Do not use floating point data types