使用c#提取括号中的字符串

Extract string in parentheses using c#

我有一个字符串---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---

我想获取 [] 内的值(即 1508825516987

如何使用正则表达式获取值?

解释:

  • \[ : [ 是一个元字符,如果你想从字面上匹配它,需要进行转义。
  • (.*?) : 以非贪婪的方式匹配所有内容并捕获它。
  • \] : ] 是一个元字符,如果你想从字面上匹配它,需要进行转义。

解释来源:Click

static void Main(string[] args)
{
    string txt = "---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---";

    Regex regex = new Regex(@"\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match match = regex.Match(txt);
    if (match.Success)
    {
        for (int i = 1; i < match.Groups.Count; i++)
        {
            String extract = match.Groups[i].ToString();
            Console.Write(extract.ToString());
        }
    }
    Console.ReadLine();
}

学习创建正则表达式的链接:

更新 1:

Regex regex = new Regex(@"^---.*\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
  • ^ 是字符串的开始
  • --- 是你的(起始)字符
  • .* 是 --- 和 [
  • 之间的任何字符

您可以使用以下代码得到您想要的结果!

 MatchCollection matches = Regex.Matches("---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---", @"\[(.*?)\]", RegexOptions.Singleline);
 Match mat = matches[0];
 string val = mat.Groups[1].Value.ToString();

而字符串 val 将包含您需要的值。