正则表达式在字符串中检索字符串

Regex Retrieving String within String

我有这两个字符串:

 s = t 
 [ f ] s = t

并使用此模式使用正则表达式处理每个:

(?<=]).*(?==|:)

我的目标是尝试通过 "[ f ]" is optional 检索 " s " part (between the "]" and "="),正如您在第一行中看到的那样。

我尝试了很多在网上找到并被其他人使用的不同模式,还花了最后 2 个小时尝试通过参考、搜索引擎、反复试验来解决这个问题,但没有成功。

我将如何实现这一目标?我需要什么模式才能实现这一点?

为什么不使用常规的 .NET 方法而不是使用 RegEx?永远记住,正则表达式不是灵丹妙药。需要几行代码的操作很快就会在 RegEx 中变得一团糟。

您的案例可以通过以下功能解决:

static string GetKey(string line)
{
    string result = line.Split('=')[0];
    if (result.IndexOf('[') < result.IndexOf(']')) // preceded by an optional group
        result = result.Split(']')[1];

    return result;
}

运行 您的代码通过此函数成功检索了每一行的 s

您可以使用正则表达式来完成这项任务。基本上,s 必须是 ] 之间的一些文本字符串或 line/string 的开头和 = 符号。

所以,使用

(?:^\p{Zs}*|])([^]=]*)=

查看regex demo

正则表达式细分:

  • (?:^\p{Zs}*|]) - 非捕获组匹配 2 个备选方案:
    • ^\p{Zs}* - string/line 的开始(取决于使用的 RegexOptions)后跟 0 个或多个水平空白符号或...
    • ] - 文字 ] 符号
  • ([^]=]*) -(捕获组 1)0 个或多个不是 ]=.
  • 的符号
  • = - 文字 = 符号

C# Code:

var strs = new List<string> { " [ f ] s = t", "s = t"};
var pattern = @"(?:^\p{Zs}*|])([^]=]*)=";
foreach (var s in strs)
{
    var match = Regex.Match(s, pattern);
    if (match.Success)
        Console.WriteLine(match.Groups[1].Value);
   }

如果你需要通过Match.Value获取你需要的值,你可以使用

@"(?<=^\p{Zs}*|])[^]=:]*(?=[=:])"

这是regex demo