加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:00:04 所属栏目:百科 来源:网络整理
导读:我试图从文本文件中取出日期.这是内容: 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:
我试图从文本文件中取出日期.这是内容:

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,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})/

这在regex101中完美运行.请参阅https://regex101.com/r/MB7yB4/1上的示例
然而,在Powershell中,它的反应不同.

$var -match "([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})"

什么都没有.
我不确定为什么比赛不一样.
?谢谢你的帮助!

解决方法

-match运算符返回一个布尔值,显示是否找到匹配项.此外,它还使用匹配数据(整个匹配和捕获组值)设置$matches变量.你只需要访问整场比赛:

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

见Using -match and the $matches variable in PowerShell.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读