C# Regex Split - 方括号内的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/740642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Regex Split - everything inside square brackets
提问by Jo?o Pereira
I'm currently trying to split a string in C# (latest .NET and Visual Studio 2008), in order to retrieve everything that's inside square brackets and discard the remaining text.
我目前正在尝试在 C#(最新的 .NET 和 Visual Studio 2008)中拆分一个字符串,以便检索方括号内的所有内容并丢弃剩余的文本。
E.g.: "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]"
例如:“H1 受体拮抗剂 [HSA:3269] [PATH:hsa04080(3269)]”
In this case, I'm interested in getting "HSA:3269" and "PATH:hsa04080(3269)" into an array of strings.
在这种情况下,我有兴趣将“ HSA:3269”和“ PATH:hsa04080(3269)”放入一个字符串数组中。
How can this be achieved?
如何做到这一点?
采纳答案by Konrad Rudolph
Split
won't help you here; you need to use regular expressions:
Split
不会在这里帮助你;您需要使用正则表达式:
// using System.Text.RegularExpressions;
// pattern = any number of arbitrary characters between square brackets.
var pattern = @"\[(.*?)\]";
var query = "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]";
var matches = Regex.Matches(query, pattern);
foreach (Match m in matches) {
Console.WriteLine(m.Groups[1]);
}
Yields your results.
产生你的结果。
回答by BobSpring
Try this
尝试这个
string mystr = "Hello my name is {robert} and i live in {florida}";
List<string> myvariables = new List<string>();
while (mystr.Contains("{"))
{
myvariable.Add(mystr.Split('{', '}')[1]);
mystr = mystr.Replace("{" + mystr.Split('{', '}')[1] + "}", "");
};
This way I will have an array which will contain robert and florida.
这样我就会有一个包含 robert 和 florida 的数组。