我有一个表示错误代码的文本文件,如下所示。我想用它作为重新学习正则表达式的练习(我曾经在几年前就知道正则表达式并且所有知识都已消失)。规格如下
我只需要来自以"public const int "
开头的行的数据。我通过使用get-content,读取循环中的每一行以及执行包含搜索来计算这部分。如果有更好的方式我就是这么多年。
假设以下一行:
" public const int TRANSACTION_E_INVALID_ACCOUNT_STATUS = 141080; //""Invalid account status""
"
我需要以下三个字段:
如果有一个教程解释如何解析像这样的一行,我也是耳朵。
谢谢,
尼克
" public const int TRANSACTION_E_INVALID_ACCOUNT_STATUS = 141080; //""Invalid account status"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1707:IdentifiersShouldNotContainUnderscores"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"TRANSACTION"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"RACE"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"CONDITION"""" )]"" "
" public const int TRANSACTION_E_TRANSACTION_RACE_CONDITION = 141081; //""Same transaction was processed by other thread"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"UNSUPPORTED"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1707:IdentifiersShouldNotContainUnderscores"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"TRANSACTION"""" )]"" "
" [SuppressMessage( ""xxxx.Naming"" "" """"CA1709:IdentifiersShouldBeCasedCorrectly"""""" "" MessageId = """"OPERATION"""" )]"" "
答案 0 :(得分:0)
我想出来了:
$line -match 'public const int (?<TranCode>.* ).*= (?<CPReturnCode>\d+).*"(?<TranDesc>.*)"'
结果
$Matches.TranCode = BDK_E_TOKEN_ALREADY_BLACKLISTED
$Matches.CPReturnCode = 5010
$Matches.TranDesc = The token is already blacklisted.
关于我认为这个表达方式如何运作的叙述:
-TranCode是&#34; public const int&#34;之后的所有字符。
-Skip任意数量的字符直到&#34; =&#34; (等号和空格)。
然后-CPReturnCode等于任意位数(\ d +)。
-Skip任意数量的字符,直到下一个&#39;&#39;&#39; (双引号)
-TranDesc等于任何数量的字符,直到下一个&#39;&#39;&#39; (双引号)
尼克
答案 1 :(得分:0)
(?=.*public const int).*?(\w+)\s*(?==).\s*(\d+).*?"([\w\s]+)
试试这个。抓住捕获。参见演示。