正则表达式过滤字符串并将结果作为列表获取
Regex to filter string and get results as a list
我有以下格式的字符串:
\r\nab-CD:2\r\nab-EF:1\r\nbc-DE:3\r\ndz-LF:1\r\nkr-TZ:2\r\nef-DD:1\r\nlv-ER:2\r\ndf-QW:3\r
我必须过滤掉值为 1
的 xx-XX
个值。 (xx-XX:1
)
所以在示例字符串中,我必须得到的值是
ab-EF
dz-LF
ef-DD
哪个正则表达式会给我结果列表?
谢谢
您可以将 Regex.Matches
与以下正则表达式一起使用
[a-z]{2}-[A-Z]{2}(?=:1)
代码:
var list = Regex.Matches(input, @"[a-z]{2}-[A-Z]{2}(?=:1)")
.Cast<Match>()
. .Select(match => match.Value).ToList();
[a-z]{2}-[A-Z]{2}(?=:1)
试试看演示。
https://regex101.com/r/fA6wE2/15
NODE EXPLANATION
--------------------------------------------------------------------------------
[a-z]{2} any character of: 'a' to 'z' (2 times)
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
[A-Z]{2} any character of: 'A' to 'Z' (2 times)
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
:1 ':1'
--------------------------------------------------------------------------------
) end of look-ahead
我有以下格式的字符串:
\r\nab-CD:2\r\nab-EF:1\r\nbc-DE:3\r\ndz-LF:1\r\nkr-TZ:2\r\nef-DD:1\r\nlv-ER:2\r\ndf-QW:3\r
我必须过滤掉值为 1
的 xx-XX
个值。 (xx-XX:1
)
所以在示例字符串中,我必须得到的值是
ab-EF
dz-LF
ef-DD
哪个正则表达式会给我结果列表?
谢谢
您可以将 Regex.Matches
与以下正则表达式一起使用
[a-z]{2}-[A-Z]{2}(?=:1)
代码:
var list = Regex.Matches(input, @"[a-z]{2}-[A-Z]{2}(?=:1)")
.Cast<Match>()
. .Select(match => match.Value).ToList();
[a-z]{2}-[A-Z]{2}(?=:1)
试试看演示。
https://regex101.com/r/fA6wE2/15
NODE EXPLANATION
--------------------------------------------------------------------------------
[a-z]{2} any character of: 'a' to 'z' (2 times)
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
[A-Z]{2} any character of: 'A' to 'Z' (2 times)
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
:1 ':1'
--------------------------------------------------------------------------------
) end of look-ahead