如何在 PowerShell 中使用变量作为正则表达式的一部分 [英] How to use a variable as part of a regular expression in PowerShell

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

问题描述

我想Select-String 文件路径的一部分,以包含在变量中的字符串值开始.让我用一个抽象的例子来解释这一点.

I want to Select-String parts of a file path starting at a string value that is contained in a variable. Let me explain this in an abstracted example.

让我们假设这个路径:/docs/reports/testreports/document1.docx

Let's assume this path: /docs/reports/test reports/document1.docx

使用正则表达式,我可以获得所需的字符串,如下所示:'^.*(?=\/test\s)'

Using a regular expression I can get the required string like so: '^.*(?=\/test\s)'

https://regex101.com/r/6mBhLX/5

结果字符串是'/test reports/document1.docx'.

The resulting string is '/test reports/document1.docx'.

现在,为了让它起作用,我必须使用文字字符串test".但是,我想知道如何使用包含test"的变量,例如$myString.

Now, for this to work I have to use the literal string 'test'. However, I would like to know how to use a variable that contains 'test', e.g. $myString.

我已经看过怎么做您在正则表达式中使用了变量吗?,但我不知道如何为 PowerShell 进行调整.

I already looked at How do you use a variable in a regular expression?, but I couldn't figure out how to adapt this for PowerShell.

推荐答案

我建议在双引号字符串文字中使用 $([regex]::escape($myString)):

I suggest using $([regex]::escape($myString)) inside a double quoted string literal:

$myString="[test]"
$pattern = "^.*(?=/$([regex]::escape($myString))\s)"

或者,如果您不想担心额外的转义,请使用 + 运算符使用常规连接:

Or, in case you do not want to worry with additional escaping, use a regular concatenation using + operator:

$pattern = '^.*(?=/' + [regex]::escape($myString) +'\s)'

结果 $pattern 看起来像 ^.*(?=/\[test]\s).由于 $myString 变量是一个文字字符串,您需要转义所有可能在其中的特殊正则表达式元字符(使用 [regex]::escape())正则表达式引擎将其解释为文字字符.

The resulting $pattern will look like ^.*(?=/\[test]\s). Since the $myString variable is a literal string, you need to escape all special regex metacharacters (with [regex]::escape()) that may be inside it for the regex engine to interpret it as literal chars.

在你的情况下,你可以使用

In your case, you may use

$s = '/docs/reports/test reports/document1.docx'
$myString="test"
$pattern = "^.*(?=/$([regex]::escape($myString))\s)"
$s -replace $pattern

结果:/test reports/document1.docx

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

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