两个特殊字符之间的字符串的Powershell正则表达式 [英] Powershell regex for string between two special characters

查看:53
本文介绍了两个特殊字符之间的字符串的Powershell正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件名如下

$inpFiledev = "abc_XYZ.bak"

我只需要变量中的 XYZ 即可与其他文件名进行比较.我在下面试过:

I need only XYZ in a variable to do a compare with other file name. i tried below:

[String]$findev = [regex]::match($inpFiledev ,'_*.').Value
Write-Host $findev

推荐答案

正则表达式中星号的行为方式与它们在文件系统列表命令中的行为方式不同.就目前而言,您的正则表达式正在寻找下划线,重复零次或多次,后跟任何字符(在正则表达式中用句点表示).所以正则表达式在字符串的开头找到零个下划线,然后找到'a',这就是它返回的匹配项.

Asterisks in regex don't behave in the same way as they do in filesystem listing commands. As it stands your regex is looking for underscore, repeated zero or more times, followed by any character (represented in regex by a period). So the regex finds zero underscores right at the start of the string, then it finds 'a', and that's the match it returns.

首先,纠正这一点:

'_*.'

变成下划线,后跟任意数量的字符,后跟文字句点".文字句点"意味着我们需要使用 \. 对正则表达式中的句点进行转义,记住句点表示任何字符:

Becomes "underscore, followed by any number of characters, followed by a literal period". The 'literal period' means we need to escape the period in the regex, by using \., remembering that period means any character:

'_.*\.'

  • _ 下划线
  • .* 任意数量的字符
  • \. 文字句点
    • _ underscore
    • .* any number of characters
    • \. a literal period
    • 返回:

      _XYZ.

      所以,不远了.

      如果您希望从字符之间返回某些内容,则需要使用捕获组.在要保留的位周围加上括号:

      If you're looking to return something from between characters, you'll need to use capturing groups. Put parentheses around the bit you want to keep:

      '_(.*)\.'
      

      然后您需要使用 PowerShell 正则表达式组来获取值:

      Then you'll need to use PowerShell regex groups to get the value:

      [regex]::match($inpFiledev ,'_(.*)\.').Groups[1].Value
      

      返回:XYZ

      Groups[1] 中的数字 1 仅表示第一个捕获组,您可以使用更多括号在表达式中添加任意数量的括号,但在这种情况下您只需要一个.

      The number 1 in the Groups[1] just means the first capturing group, you can add as many as you like to the expression by using more parentheses, but you only need one in this case.

      这篇关于两个特殊字符之间的字符串的Powershell正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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