0

I have a regular expression that works perfectly in Sublime text, or other text editors, and it does exactly what I need it to do.

Here is the regular expression

(?sm),"([\w\W]*?)Date completed: 

The problem is, in PowerShell, it just doesn't do anything.

This is my little script

$text = Get-Content c:\Tools\export.csv
$text -replace '(?sm),"([\w\W]*?)Date completed: ','REPLACED' | Out-File output.csv

If I replace the regular expression by plain text, it works great. So what is it that it does not like in my regular expression?

Thanks!

4
  • What do you mean by 'plain text' ? Commented Apr 8, 2016 at 18:09
  • if I replace the regular expression by something like 'Example' it will find Example and replace it with REPLACED. Commented Apr 8, 2016 at 18:12
  • That comma and open double quote in here '(?sm),"([\w\W]*?)Date completed: ' it is expecting a comma and double quote which I don't think exists in your source data that you are not including here. More impotantly you need to change you $text to be a single string if you expect to use the single and multi mode. $text = Get-Content c:\Tools\export.csv | out-string... im just doing to write and answer. Commented Apr 8, 2016 at 18:25
  • If a regex is not working we need source examples. Else it is impossible to know what is wrong. Show us how you made it work. Commented Apr 8, 2016 at 18:28

2 Answers 2

1

Regardless of what you are trying to match against when you use single and multimode those are supposed to work on multi-lined strings. Get-Content by default will return a string array. -replace functions as an array operator and will run that pattern against each line individually.

So for starters make $text one string.

$text = Get-Content c:\Tools\export.csv | Out-String

Or if you have at least PowerShell 3.0

$text = Get-Content c:\Tools\export.csv -Raw
Sign up to request clarification or add additional context in comments.

Comments

0

Based on the info I got from the people who answered, here is how I was able to accomplish what I needed to do for the regular expression

$text = (Get-Content c:\Tools\export.csv) | out-string

$regex = "(?sm),""\s.*?Date completed: "
$replace = ',"'
$output = [regex]::replace($text,$regex,$replace)

$output | Out-file c:\Tools\output.csv -Encoding ascii

Comments

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.