如何在括号之间获取文本

时间:2017-09-07 02:44:42

标签: c#

所以我试图在C#中的括号之间插入文本。

我想从SYSTEM获得[SYSTEM]: Welcome

(所有已知实例)

我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:2)

我不确定所有已知实例的含义,但您可以使用

// to extract a single substring split should do the job
var input = "[SYSTEM]: Welcome";
var output = input.Split('[', ']')[1];

// output will be SYSTEM

// for multiple occurances you can use regular expression
var inputTwo = "[SYSTEM]: Welcome [other]";

var pattern = @"\[([^\[\]]+)\]";

var outputs = new List<string>();

foreach (Match match in Regex.Matches(inputTwo, pattern))
{
    outputs.Add(match.Groups[1].Value);
}

//  outputs will be ["SYSTEM", "other"]
相关问题