我遇到了一些问题。我试图分割一些文字和数字。
考虑此字符串输入。
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
我试图让2:3,2:6,5:4从文本的其余部分中分离出来。 然后我希望它们与冒号分开,并添加到列表中。
在循环之后,列表看起来像这样。 2 3 2 6 五 4
我可以从[0]和[1],[2]和[3],[4]和[5]创建一个Hashtable条目。
我想感谢大家对此的反馈。
答案 0 :(得分:2)
如果我理解你的问题,我会这样做
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
var table = Regex.Matches(input, @"(\d+):(\d+)")
.Cast<Match>()
.ToLookup(m => m.Groups[1].Value, m => m.Groups[2].Value);
答案 1 :(得分:1)
使用正则表达式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
string pattern = @"(?'index'\d+)\s+(?'name'\w+)\s+(?'para'\d+:\d+),?";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("index : {0}, name : {1}, para : {2}",
match.Groups["index"],
match.Groups["name"],
match.Groups["para"]
);
}
Console.ReadLine();
}
}
}
答案 2 :(得分:0)
这里有一些可以帮助你的代码。
var input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
var nextIndex = 0;
var currentIndex = 0;
var numbers = new List<int>();
do
{
currentIndex = input.IndexOf(":", currentIndex + 1);
var leftNumber = Convert.ToInt32(input[currentIndex - 1].ToString());
var rightNumber = Convert.ToInt32(input[currentIndex + 1].ToString());
numbers.Add(leftNumber);
numbers.Add(rightNumber);
nextIndex = input.IndexOf(":", currentIndex + 1);
} while (nextIndex != -1);