3

I'm trying to see if there is an entry for some input in a file, so I'm using a regular expression to query each line:

cat $file | where {$_ -match "^script\$fileName -*"}

where $fileName is some input defined elsewhere.

How do I alter the regex to interpolate the variable instead of matching for '$fileName' ?

1
  • 2
    I think it's because you escape $. Try leaving out the backslash. If you want to match a literal backslash, add a second backslash instead (to escape the backslash). Commented Nov 7, 2012 at 23:43

3 Answers 3

9

In addition to the answer given, as $fileName could contain characters such as '.' or '\' you should escape it as follows:

cat $file | where {$_ -match "^script\\$([regex]::Escape($fileName)) -*"}

The Escape method will escape bits like '.' and '\' for you.

E.g.

[regex]::Escape(".\bar.txt")

gives

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

Comments

3

$fileName gets interpolated so you wind up with a string passed to regex that looks like this:

cat $file | where {$_ -match "^script\foo.txt -*"}

The \ is acting as an escape character for the following character when in fact we want a liternal \ to matched against. In this case, you'll need to escape the escape character e.g.:

cat $file | where {$_ -match "^script\\$fileName -*"}

2 Comments

hi, \\ means \ in regular expression. so the first \ is escaping the second \ for regular expression. in powershell, ` is used for escaping instead of \, so $ is not escaped.
Yeah, we simply want the backslash escaped so that it can be used to match the path separator. I'll update the answer to reflect this.
0

It is also possible to break the RegEx up inside of powershell.

$fileName = 'test'
'^script\test-*' -match ('\^script\\' + $fileName + '-*')

More readable and will work with multidimensional arrays where variable has brackets []

$fileName = New-Object object[][] 1
$fileName[0] = @('test')
'^script\test-*' -match ('\^script\\' + $fileName[0][0] + '-*')

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.