获取大括号之间的值 c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17379482/
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
Get values between curly braces c#
提问by Kurubaran
I never used regex before. I was abel to see similar questions in forum but not exactly what im looking for
我以前从未使用过正则表达式。我在论坛上看到了类似的问题,但不完全是我要找的
I have a string like following. need to get the values between curly braces
我有一个像下面这样的字符串。需要获取大括号之间的值
Ex: "{name}{[email protected]}"
例如:“{name}{[email protected]}”
And i Need to get the following splitted strings.
我需要获得以下拆分字符串。
name and [email protected]
姓名和姓名@gmail.com
I tried the following and it gives me back the same string.
我尝试了以下操作,它给了我相同的字符串。
string s = "{name}{[email protected]}";
string pattern = "({})";
string[] result = Regex.Split(s, pattern);
采纳答案by Jan Dobkowski
Is using regex a must? In this particular example I would write:
必须使用正则表达式吗?在这个特定的例子中,我会写:
s.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
回答by sangram parmar
here you go
干得好
string s = "{name}{[email protected]}";
s = s.Substring(1, s.Length - 2);// remove first and last characters
string pattern = "}{";// split pattern "}{"
string[] result = Regex.Split(s, pattern);
or
或者
string s = "{name}{[email protected]}";
s = s.TrimStart('{');
s = s.TrimEnd('}');
string pattern = "}{";
string[] result = Regex.Split(s, pattern);
回答by Fabian Bigler
Use Matchesof Regexrather than Splitto accomplish this easily:
使用Matches的Regex,而不是Split来轻松地完成这一点:
string input = "{name}{[email protected]}";
var regex = new Regex("{(.*?)}");
var matches = regex.Matches(input);
foreach (Match match in matches) //you can loop through your matches like this
{
var valueWithoutBrackets = match.Groups[1].Value; // name, [email protected]
var valueWithBrackets = match.Value; // {name}, {[email protected]}
}

