如何从字符串中获取特定元素

时间:2013-02-26 21:29:23

标签: c# string parsing

我需要能够从以大括号开头和结尾的字符串中获取特定元素。如果我有一个字符串:

  

“asjfaieprnv {1} oiuwehern {0} oaiwefn”

我怎么能抓住1后跟0。

3 个答案:

答案 0 :(得分:3)

正则表达式非常有用。

您想要匹配的是:

\{   # a curly bracket
     # - we need to escape this with \ as it is a special character in regex
[^}] # then anything that is not a curly bracket
     # - this is a 'negated character class'
+    #  (at least one time)
\}   # then a closing curly bracket
     # - this also needs to be escaped as it is special

我们可以将其折叠为一行:

\{[^}]+\}

接下来,您可以通过围绕要用括号提取的部分来捕获和提取内部内容,以形成

\{([^}]+)\}

在C#中你会这样做:

var matches = Regex.Matches(input, @"\{([^}]+)\}");
foreach (Match match in matches)
{
    var groupContents = match.Groups[1].Value;
}

组0是整个匹配(在这种情况下包括{}),组1是第一个带括号的部分,依此类推。

一个完整的例子:

var input = "asjfaieprnv{1}oiuwehern{0}oaiwef";
var matches = Regex.Matches(input, @"\{([^}]+)\}");
foreach (Match match in matches)
{
    var groupContents = match.Groups[1].Value;
    Console.WriteLine(groupContents);
}

输出:

1
0

答案 1 :(得分:1)

使用Indexof方法:

int openBracePos = yourstring.Indexof ("{");
int closeBracePos = yourstring.Indexof ("}");
string stringIWant = yourstring.Substring(openBracePos, yourstring.Len() - closeBracePos + 1);

这将是你第一次出现。您需要对字符串进行切片,以便第一次出现不再存在,然后重复上述过程以找到第二次出现:

yourstring = yourstring.Substring(closeBracePos + 1);

注意:你可能需要逃避花括号:“{” - 不确定这个;从来没有用C#

处理它们

答案 2 :(得分:0)

这看起来像是正则表达式的作业

using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "asjfaieprnv{1}oiuwe{}hern{0}oaiwefn";
            Regex regex = new Regex(@"\{(.*?)\}");

            foreach( Match match in regex.Matches(str))
            {
                 Console.WriteLine(match.Groups[1].Value);
            }
        }
    }
}