简体   繁体   English

C#“字符串之间”运行多次

[英]C# "between strings" run several times

Here is my code to find a string between { } :这是我在{ }之间查找字符串的代码:

var text = "Hello this is a {Testvar}...";
int tagFrom = text.IndexOf("{") + "{".Length;
int tagTo = text.LastIndexOf("}");
String tagResult = text.Substring(tagFrom, tagTo - tagFrom);

tagResult Output: Testvar tagResult 输出: Testvar

This only works for one time use.这仅适用于一次使用。 How can I apply this for several Tags?如何将其应用于多个标签? (eg in a While loop) (例如在 While 循环中)

For example:例如:

var text = "Hello this is a {Testvar}... and we have more {Tagvar} in this string {Endvar}.";

tagResult[] Output (eg Array): Testvar , Tagvar , Endvar tagResult[]输出(例如数组): Testvar , Tagvar , Endvar

IndexOf() has another overload that takes the start index of which starts to search the given string. IndexOf()有另一个重载,它采用开始搜索给定字符串的起始索引。 if you omit it, it will always look from the beginning and will always find the first one.如果省略它,它将始终从头开始查找并始终找到第一个。

 var text = "Hello this is a {Testvar}...";
    int start = 0, end = -1;
    List<string> results = new List<string>();
    while(true)
    {
        start = text.IndexOf("{", start) + 1;
        if(start != 0)
           end = text.IndexOf("}", start);
        else
           break;
        if(end==-1) break;
        results.Add(text.Substring(start, end - start));
        start = end + 1;  
    }

I would use Regex pattern {(\\\\w+)} to get the value.我会使用正则Regex模式{(\\\\w+)}来获取值。

Regex reg = new Regex("{(\\w+)}");     
var text = "Hello this is a {Testvar}... and we have more {Tagvar} in this string {Endvar}.";
string[] tagResult = reg.Matches(text)
    .Cast<Match>()
    .Select(match => match.Groups[1].Value).ToArray();
foreach (var item in tagResult)
{
    Console.WriteLine(item);
}

c# online c#在线

Result结果

Testvar
Tagvar
Endvar

I strongly recommend using regular expressions for the task.我强烈建议在任务中使用正则表达式。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var regex = new Regex(@"(\{(?<var>\w*)\})+", RegexOptions.IgnoreCase);
            var text = "Hello this is a {Testvar}... and we have more {Tagvar} in this string {Endvar}.";
            var matches = regex.Matches(text);

            foreach (Match match in matches)
            {
                var variable = match.Groups["var"];
                Console.WriteLine($"Found {variable.Value} from position {variable.Index} to {variable.Index + variable.Length}");
            }
        }        
    }
}

Output:输出:

Found Testvar from position 17 to 24从位置 17 到 24 找到 Testvar

Found Tagvar from position 47 to 53从位置 47 到 53 找到 Tagvar

Found Endvar from position 71 to 77从位置 71 到 77 找到 Endvar

For more information about regular expression visit the MSDN reference page:有关正则表达式的更多信息,请访问 MSDN 参考页面:

https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

and this tool may be great to start testing your own expressions:这个工具可能非常适合开始测试您自己的表达式:

http://regexstorm.net/tester http://regexstorm.net/tester

Hope this help!希望这有帮助!

Many ways to skin this cat, here are a few:给这只猫剥皮的方法很多,这里有一些:

  • Split it on { then loop through, splitting each result on } and taking element 0 each time在 { 上拆分,然后循环遍历,在 } 上拆分每个结果并每次取元素 0

  • Split on { or } then loop through taking only odd numbered elements在 { 或 } 上拆分,然后循环只取奇数元素

  • Adjust your existing logic so you use IndexOf twice (instead of lastindexof).调整您现有的逻辑,以便您使用 IndexOf 两次(而不是 lastindexof)。 When you're looking for a } pass the index of the { as the start index of the search当您寻找 } 时,将 { 的索引作为搜索的起始索引

This is so easy by using Regular Expressions just by using a simple pattern like {([\\d\\w]+)} .通过使用像{([\\d\\w]+)}这样的简单模式,使用正则表达式非常容易。 See the example below:-请参阅以下示例:-

using System.Text.RegularExpressions;
...
MatchCollection matches = Regex.Matches("Hello this is a {Testvar}... and we have more {Tagvar} in this string {Endvar}.", @"{([\d\w]+)}");
foreach(Match match in matches){
    Console.WriteLine("match : {0}, index : {1}", match.Groups[1], match.index);
}

It can find any series of letters or number in these brackets one by one.它可以在这些括号中一一找到任何系列的字母或数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM