重复子字符串N次

时间:2019-04-04 10:26:42

标签: c# regex

我收到一系列字符串,后接非负数,例如"a3"。我必须在控制台上打印每个重复N次(大写)的字符串,其中N是输入中的数字。在示例中,结果为:"AAA"。如您所见,我尝试从输入中获取数字,并且我认为它工作正常。您能帮我重复吗?

string input = Console.ReadLine();
//input = "aSd2&5s@1"
MatchCollection matched = Regex.Matches(input, @"\d+");
List<int> repeatsCount = new List<int>();

foreach (Match match in matched)
{
    int repeatCount = int.Parse(match.Value);
    repeatsCount.Add(repeatCount);
}
//repeatsCount: [2, 5, 1]
//expected output: ASDASD&&&&&S@ ("aSd" is converted to "ASD" and repeated twice;
// "&" is repeated 5 times; "s@" is converted to "S@" and repeated once.)

例如,如果我们有“ aSd 2 5 s @ 1 ”: "aSd"转换为"ASD"并重复两次"&"重复 5次"s@"将转换为"S@",并重复一次

5 个答案:

答案 0 :(得分:3)

让模式包括两个组:要重复的value和要重复的times个数量:

@"(?<value>[^0-9]+)(?<times>[0-9]+)"

然后我们可以在 Linq 的帮助下对这些进行操作:

  string source = "aSd2&5s@1";

  string result = string.Concat(Regex
    .Matches(source, @"(?<value>[^0-9]+)(?<times>[0-9]+)")
    .OfType<Match>()
    .SelectMany(match => Enumerable                        // for each match
       .Repeat(match.Groups["value"].Value.ToUpper(),      // repeat "value"
               int.Parse(match.Groups["times"].Value))));  // "times" times 

  Console.Write(result);

结果:

ASDASD&&&&&S@

编辑:相同的想法没有Linq

  StringBuilder sb = new StringBuilder();

  foreach (Match match in Regex.Matches(source, @"(?<value>[^0-9]+)(?<times>[0-9]+)")) {
    string value = match.Groups["value"].Value.ToUpper();
    int times = int.Parse(match.Groups["times"].Value);

    for (int i = 0; i < times; ++i)
      sb.Append(value);
  }

  string result = sb.ToString();

答案 1 :(得分:1)

您可以提取子字符串以及使用此正则表达式重复的频率:

var results = myInputSequence.GroupBy(

    // parameter KeySelector: make groups of inputItems that have equal HealthPlan
    inputItem => inputItem.HealthPlan,

    // parameter resultSelector: take the common HealthPlan, and all input items
    // that have this Healthplan to make a new object:
    (healthPlan, inputItemsWithThisHealthPlan) => new
    {
        HealthPlan = healthPlan,

        // Subgroups: take all input items with this healthplan, and group by
        // HealthMemberTypeName
        HealthMembers = inputItemsWithThisHealthPlan.GroupBy(

            // keySelector:
            inputItemWithThisHealthPlan => inputItemWithThisHealthPlan.HealthMemberTypeName,

            // ResultSelector: take the common HealthMemberTypeName and all
            // input items with this HealthPlan and this HealthMemberTypeName
            // to make one new object
            (healthMemberTypeName, inputItemsWithThisHealthMemberTypeName) => new
            {
                HealthMemberTypeName = healthMemberTypeName,

                // keep only the HealthBenefitDescriptions:
                HealthBenefitDescriptions = inputItemsWithThisHealthMemberTypeName
                   .Select(inputItemWithThisHealthMemberTypeName => inputItemsWithThisHealthMemberTypeName.HealthBenefitDescription)
                   .ToList(),
            })
            .ToList(),
       });

现在,您可以使用(?<content>.+?)(?<count>\d+) 创建输出字符串。完整代码:

StringBuilder

输出为

  

ASDASD &&&&&& S @

答案 2 :(得分:1)

没有LINQ的另一种解决方案

我试图保留解决方案,使其与您的解决方案相似

string input = "aSd2&5s@1";
var matched = Regex.Matches(input, @"\d+");
var builder = new StringBuilder();
foreach (Match match in matched)
{
     string stingToDuplicate = input.Split(Char.Parse(match.Value))[0];
     input = input.Replace(stingToDuplicate, String.Empty).Replace(match.Value, String.Empty);
      for (int i = 0; i < Convert.ToInt32(match.Value); i++)
      {
                  builder.Append(stingToDuplicate.ToUpper());
      }
 }

最后是Console.WriteLine(builder.ToString()); 结果为ASDASD&&&&&S@

答案 3 :(得分:1)

我的解决方案与其他解决方案相同,只是略有不同:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication107
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "aSd2&5s@1";
            string pattern1 = @"[a-zA-z@&]+\d+";
            MatchCollection matches = Regex.Matches(input, pattern1);

            string output = "";
            foreach(Match match in matches.Cast<Match>().ToList())
            {
                string pattern2 = @"(?'string'[^\d]+)(?'number'\d+)";
                Match match2 = Regex.Match(match.Value, pattern2);
                int number = int.Parse(match2.Groups["number"].Value);
                string str = match2.Groups["string"].Value;

                output += string.Join("",Enumerable.Repeat(str.ToUpper(), number));
            }
            Console.WriteLine(output);
            Console.ReadLine();


        }
    }


}

答案 4 :(得分:1)

非常简单的程序。没有问题,没有简单的stringfor循环。

string input = "aSd2&5s@1";
char[] inputArray = input.ToCharArray();
string output = "";

string ab = "";
foreach (char c in inputArray)
{
    int x;
    string y;
    if(int.TryParse(c.ToString(), out x))
    {
        string sb = "";
        ab = ab.ToUpper();
        for(int i=0;i<b;i++)
        {
           sb += ab;
        }
        ab = "";
        output += sb;
    }
    else
    {
        ab += c;
    }
}
if(!string.IsNullOrEmpty(ab))
{
    output += ab.ToUpper();
}
Console.WriteLine(output);

希望有帮助。