3

I am searching for following regex pattern in a file "[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+" This pattern contains all text including spaces. I am trying to Replace spaces(\s) to underscore(_) for all the entries in file that matches above pattern

(Get-Content .\temp.log -raw) -replace '("[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+")', {$($1.replace(' ','_'))}

Let me know what i am missing here.

1
  • The evaluation just doesn't happen in the order you want 'a' -replace '(a)',('$1' -replace 'a','b') Commented Sep 27, 2024 at 13:24

2 Answers 2

3

When you use a script block ({ ... }) as the substitution operand of the -replace operator (doing so is only supported in PowerShell (Core) 7), you must refer to the match at hand via the automatic $_ variable:

(Get-Content .\temp.log -raw) -replace '("[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+")', 
                                       { $_.Groups[1].Value -replace ' ', '_' }

Note:

  • .Groups[1].Value extracts the text that the first capture group ((...)) in your regex matched, because $_ contains a [System.Text.RegularExpressions.Match] instance.

    • That said, since your capture group encompasses your entire regex, you can omit the capture group and refer to the match more simply as $_.Value

As for what you tried:

Sign up to request clarification or add additional context in comments.

Comments

0

I think a simple match-THEN-replace should work for the best:

# Here keeping the regex separated for better reading.  
$RegexPattern='("[a-zA-Z0-9]+[^"]+[a-zA-Z0-9]+")'

# This will replace spaces with underscores in every line matching the Regex.  
(Get-Content .\set.txt ) -match $RegexPattern -replace ' ', '_'

1 Comment

While elegant, this isn't the same in terms of functionality, given that you're replacing spaces on each whole line that happens to match the regex as a substring. (Also, even that would fail if the file contains only one line, but that aspect is easily fixed by using @(Get-Content ...) rather than(Get-Content ...))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.