gpt4 book ai didi

c# - 正则表达式提取可变部分

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:59 26 4
gpt4 key购买 nike

我有一个包含这个的字符串:

@[User::RootPath]+"Dim_MyPackage10.dtsx"
我需要使用正则表达式提取 [User::RootPath] 部分。到目前为止,我有这个正则表达式:
[a-zA-Z0-9]*\.dtsx
但我不知道如何进行下一步。

最佳答案

对于变量,为什么不使用未设置来消费需要的东西[^ ]提取集合中除外 的所有内容?

^在大括号中表示查找匹配的内容,例如它在其中查找所有不是 ] 的内容或引号 ( " )。

然后我们可以将实际匹配放在命名的捕获组中 (?<{NameHere}> )并相应地提取

string pattern = @"(?:@\[)(?<Path>[^\]]+)(?:\]\+\"")(?<File>[^\""]+)(?:"")";
// Pattern is (?:@\[)(?<Path>[^\]]+)(?:\]\+\")(?<File>[^\"]+)(?:")
// w/o the "'s escapes for the C# parser

string text = @"@[User::RootPath]+""Dim_MyPackage10.dtsx""";

var result = Regex.Match(text, pattern);

Console.WriteLine ("Path: {0}{1}File: {2}",
result.Groups["Path"].Value,
Environment.NewLine,
result.Groups["File"].Value
);

/* Outputs
Path: User::RootPath
File: Dim_MyPackage10.dtsx
*/

(?: )匹配但不捕获,因为我们将它们用作我们模式的实际 anchor ,而不是将它们放入匹配捕获组中。

关于c# - 正则表达式提取可变部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462081/

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