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

本文关键字:元素 获取 字符串 | 更新日期: 2023-09-27 18:01:29

我需要能够从以花括号开始和结束的字符串中抓取特定元素。如果我有一个字符串

" asjfaieprnv {1} oiuwehern {0} oaiwefn"

我怎么能抓住后面跟着0的1

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

Regex在这方面非常有用。

你想要匹配的是:

'{   # 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

使用Indexof方法

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

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

yourstring = yourstring.Substring(closeBracePos + 1);

注意:你可能需要转义花括号:"{" -对此不确定;从未在c#中处理过它们

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

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);
            }
        }
    }
}