简体   繁体   English

如何使用正则表达式从文本到数组中提取少量值

[英]How can i extract using regex few values from text to array

I have text document with this pattern: 我有这种模式的文本文档:

Red fox got number1 socks: number2 and: number3 红狐得到了number1袜子:number2和:number3

Red fox got number4 socks: number5 and: number6 红狐得到了number4袜子:number5和:number6

Red fox got number7 socks: number8 and: number9 ... 红狐狸有7号袜子:号码8和:号码9 ......

I need to extract all numberx from each line and put it in array like: 我需要从每一行中提取所有numberx并将其放在数组中,如:

[number1,number2,number3] [数字1,数字,number3的]

[number4,number5,number6] [号码4,5号,number6]

[number7,number8,number9] [number7,number8,number9]

i'm using C#. 我正在使用C#。

thanks 谢谢

你的正则表达方式是: "Red fox got ([0-9]+) socks: ([0-9]+) and: ([0-9]+)"

Solution without regex: 解决方案没有正则表达式:

string input = "Red fox got 1 socks: 22 and: 333";

string[] split = input.Split(' ');

string output = string.Format("[{0},{1},{2}]", split[3], split[5], split[7]);

Put the logic in a loop and for each input add the output to a list or array. 将逻辑放在循环中,并为每个输入将输出添加到列表或数组。

class Program
{
    static void Main()
    {
        var input = File.ReadAllLines("test.txt");
        var result = input
            .Select(
                line => Regex.Matches(line, @"\d+")
                             .OfType<Match>()
                             .Select(m => m.Groups[0].Value)
            );
        foreach (string[] numbers in result)
        {
            Console.WriteLine(string.Join(",", numbers));
        }
    }
}

Given the following input file: 给定以下输入文件:

Red fox got 1 socks: 2 and: 3
Red fox got 4 socks: 5 and: 6
Red fox got 7 socks: 8 and: 9

the program prints: 程序打印:

1,2,3
4,5,6
7,8,9

Here you go 干得好

using System.Text.RegularExpressions;

foreach(var match in Regex.Matches(theText, "[0-9]+")
{
    var number = int.Parse(match.Value);
}

will allow you to iterate all numbers in the text. 将允许您迭代文本中的所有数字。 If you want them in triplets, 如果你想要三胞胎,

IEnumerable<Tuple<int,int,int>> NumberTripletsFromText(string theText)
{
    var results = new List<int>;
    var count = 0;

    foreach(var match in Regex.Matches(theText, "[0-9]+")
    {
        count++;
        results.Add(int.Parse(match.Value);

        if (count == 3)
        {
            yield return Tuple.Create(results[1], results[2], results[3]);
            results.Clear;
            count = 0;
        }
    }

    if (results > 0)
    {
       //Handle non divisible by three.
    }
}

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

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