如何在powershell中的正则表达式中插入变量 [英] How to interpolate variables in regular expressions in powershell

查看:35
本文介绍了如何在powershell中的正则表达式中插入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查看文件中是否有某些输入的条目,因此我使用正则表达式来查询每一行:

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 |其中 {$_ -match "^script\$fileName -*"}

其中 $fileName 是在别处定义的一些输入.

where $fileName is some input defined elsewhere.

如何更改正则表达式以插入变量而不是匹配 '$fileName' ?

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

推荐答案

除了给出的答案,因为 $fileName 可以包含诸如 '.' 之类的字符.或 '\' 你应该按如下方式转义它:

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)) -*"}

Escape 方法将转义像 '.' 这样的位.和 '\' 给你.

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

例如

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

给予

\.\\bar\.txt

这篇关于如何在powershell中的正则表达式中插入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆