gpt4 book ai didi

c# - 将 Notepad++ REGEX 转换为 .NET C#

转载 作者:行者123 更新时间:2023-12-01 23:29:46 25 4
gpt4 key购买 nike

使用竖线分隔的文件。目前,我使用 Notepad++ 查找并替换 REGEX 模式 ^(?:[^|]*\|){5}\K[^|]* 将第 5 行之间的所有行替换为空字符串和第 6 个 |。我正在尝试以编程方式执行此过程,但 .NET 不支持 \K。我已经尝试了几个向后查找的实例,但我似乎无法理解它。

string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
string line2 = null;
string finalLine = line;
string[] col = line.Split('|');
if (col[5] != null)
{
line2 = Regex.Replace(line, @"^(?:[^|]*\|){5}\K[^|]*", "");

最佳答案

\K是不支持锚定 look-behind assertions 的正则表达式语法/引擎的“解决方法” .

.NET 的正则表达式语法 has look-behind assertions (使用语法 (?<=subexpression) ),所以使用它们:

Regex.Replace(line, @"(?<=^(?:[^|]*\|){5})[^|]*", "")

在 .NET 的上下文中,此模式现在描述:

(?<=               # begin (positive) look-behind assertion
^ # match start of string
(?: # begin non-capturing group
[^|]*\| # match (optional) field value + delimiter
){5} # end of group, repeat 5 times
) # end of look-behind assertion
[^|]* # match any non-delimiters (will only occur where the lookbehind is satisfied)

关于c# - 将 Notepad++ REGEX 转换为 .NET C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66497484/

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