gpt4 book ai didi

正则表达式返回完整行而不是匹配

转载 作者:行者123 更新时间:2023-12-04 18:59:39 26 4
gpt4 key购买 nike

我正在尝试从文本文件中正则表达式输出日期。这是内容:

Storage Manager Command Line Administrative Interface - Version 7, Release 1, Level 1.4 (c) Copyright by Corporation and other(s) 1990, 2015. All Rights Reserved.

Session established with server TSERVER: Windows Server Version 7, Release 1, Level 5.200 Server date/time: 11/22/2016 15:30:00 Last access: 11/22/2016 15:25:00

ANS8000I Server command.



我需要在服务器日期/时间之后提取日期/时间。我写了这个正则表达式:
/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})/

这在 regex101 中非常有效。参见 https://regex101.com/r/MB7yB4/1 上的示例
但是,在 Powershell 中,它的 react 不同。
$var -match "([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})"



Server date/time: 11/22/2016 16:30:00 Last access: 11/22/2016 15:37:19




$var -match "([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})"

什么都不给。
我不知道为什么比赛不一样。
谢谢你的帮助!

最佳答案

-match运算符返回一个 bool 值,显示是否找到匹配项。此外,它还设置了 $matches带有匹配数据(整个匹配和捕获组值)的变量。您只需要访问整个比赛:

if($var -match '[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}') { $matches[0] }

Using -match and the $matches variable in PowerShell .

请注意,无需转义 /在 Powershell regexp 中使用符号,因为这个字符并不特殊,并且在 Powershell 中定义正则表达式时不使用正则表达式分隔符(在 JS、PHP 正则表达式中的那些外部 /.../)。

关于正则表达式返回完整行而不是匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40762461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com