regex - 使用 PowerShell 从文本段落中提取 6 位数字字符串导致空白数据

标签 regex powershell

尝试使用 PowerShell 从一段文本中提取 6 位数字字符串,但它仅适用于一种情况。 6 位字符串位于 Windows 剪贴板中的一段文本内。在我的代码中,我期望变量 $Matches[0] 是我要查找的 6 位数字,但结果始终为空。如果我取消第 2 行的注释,则 $Matches[0] 将始终是第 2 行中的 6 位代码,即 123456,如下所示。但是如果我注释掉第 2 行,然后从我的真实世界示例中复制一段文本,然后重新运行代码,而不是 $Matches[0] 是预期的 6 位字符串,它始终为空白。我将在下面介绍两个示例及其输出。不知道我做错了什么。
工作示例:

$Matches[0] = $null
Set-Clipboard -value "Your PIN is 123456."
$PIN = (Get-Clipboard) -match '\d{6}'
# Get-Clipboard
Write-Output $Matches[0]
上面的代码将按预期输出以下内容:
Working Example
非工作示例:
如果我注释掉第 2 行:
$Matches[0] = $null
# Set-Clipboard -value "Your PIN is 123456."
$PIN = (Get-Clipboard) -match '\d{6}'
# Get-Clipboard
Write-Output $Matches[0]
并给出这段文字,复制到 Windows 剪贴板中:

Hello,

Your authentication code is 351370

This code will expire in 20 minutes to keep your account secure.


输出显示空白,而不是预期的 351370:
Non-working Example
想法?

最佳答案

问题 :

  • Get-Clipboard cmdlet 将多行文本作为字符串数组返回。
  • 以数组为 LHS , -match , regular-expression matching operator作为过滤器返回匹配元素的子数组(就像其他比较运算符所做的那样 - 参见 about_Comparison_Operators ),在这种情况下 automatic $Matches variable未填充 .

  • 解决方案 是到 请求剪贴板上的文本为单个多行字符串 , 使用
    -Raw 转变:
    if ((Get-Clipboard -Raw) -match '\d{6}') {
      $Matches[0] # -> '351370'
    }
    

    替代 是使用 -replace , regex-based string-replacement operator ,这需要匹配整个字符串并将其替换为捕获组匹配的内容:
    @'
    Hello,
    
    Your authentication code is 351370
    
    This code will expire in 20 minutes to keep your account secure
    '@ -replace '(?s).*(\d{6}).*', '$1' # -> 351370
    
    笔记:
  • 内联选项 s ( SingleLine ; ( (?s) ) 确保 . 也匹配换行符 ( \n ) 字符,以启用跨多行字符串的所有行的匹配。
  • 在替换操作数中,$1指的是第一个(也是唯一一个)捕获组 ( (...) ) 捕获的内容。
  • 警告:如果正则表达式与输入不匹配,则输入字符串按原样返回。

  • 最后,直接使用 .NET API 通过 [regex]类 ( System.Text.RegularExpressions.Regex ) 是 另一种选择 ,如图 santisq's answer ,但它需要高级知识 在 PowerShell 自己的命令和运算符的范围之外。

    关于regex - 使用 PowerShell 从文本段落中提取 6 位数字字符串导致空白数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66607045/

    相关文章:

    java - java 7中unicode的正则表达式

    arrays - 如何将 AD 计算机名称传递给数组?

    Powershell读取文本文件等到找到然后继续

    Python 2.7 与 BeautifulSoup 错误 : Cannot process flags argument with a compiled pattern

    regex - 匹配具有相同字母的单词

    regex - "=~"提高 "No instance for (RegexContext Regex [Char] [String])"

    Java正则表达式文件名不重复

    linux - 使用 powershell 将 Linux shell 脚本文件从 Windows 插入到 Linux box

    powershell - 在 PowerShell 1.0 中使用带有制表符的字符串拆分

    Powershell - Outlook - 将多个附件添加到电子邮件