[英]How to search string for a specific substring and get a number associated with that substring?
I am a newbie learning C# and this is the task at hand: I have a text file with a some JSON in it.我是一个学习 C# 的新手,这是手头的任务:我有一个包含一些 JSON 的文本文件。 In the text file there are multiple lines and each paragraph is separated from the next through an empty line.
在文本文件中有多行,每个段落通过一个空行与下一个段落分隔。
I want to get the number associated with the substring "Label " + number.我想获取与子字符串“标签”+数字关联的数字。 See below.
见下文。
This is an example of the input from the text file:这是来自文本文件的输入示例:
{"menu": {"header": "menu", "items": [{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]}}
{“菜单”:{“标题”:“菜单”,“项目”:[{“id”:27},{“id”:0,“标签”:“标签0”},null,{“id” :93},{“id”:85},{“id”:54},空,{“id”:46,“标签”:“标签46”}]}}
{"menu": {"header": "menu", "items": [{"id": 81}]}}
{“菜单”:{“标题”:“菜单”,“项目”:[{“id”:81}]}}
{"menu": {"header": "menu", "items": [{"id": 70, "label": "Label 70"}, {"id": 85, "label": "Label 85"}, {"id": 93, "label": "Label 93"}, {"id": 2}]}}
{“菜单”:{“标题”:“菜单”,“项目”:[{“id”:70,“标签”:“标签70”},{“id”:85,“标签”:“标签85 "}, {"id": 93, "label": "标签 93"}, {"id": 2}]}}
What I've done so far is:到目前为止我所做的是:
static void Main(string[] args)
{
string path = @"C:\Users\X\Desktop\docomentul.txt";
string jSONstring;
string resultString;
string labelString = "Label ";
using (StreamReader reader = File.OpenText(path))
{
jSONstring = reader.ReadToEnd();
var jSONlines = Regex.Split(jSONstring,"(?m)^\\s*$");
foreach (var line in jSONlines)
{
resultString = Regex.Match(line, @"\d+").Value;
Console.WriteLine(resultString);
}
}
Console.ReadKey();
}
Now this only brings back the first occurrence of a number in the string.现在这只会带回字符串中第一次出现的数字。 What I want is to find each occurrence of the numbers associated with the substring "Label ".
我想要的是找到与子字符串“Label”相关的数字的每次出现。 At least that is how I planned on solving this.
至少这就是我计划解决这个问题的方式。 However I don't really know how to use REGEX nor how to find it in another way.
但是我真的不知道如何使用 REGEX 也不知道如何以另一种方式找到它。
Once I get the numbers associated with the substring "Label ", I will have to add them for each item and then print out the sum for each string in the array (or paragraph).一旦我得到与子字符串“Label”关联的数字,我将不得不为每个项目添加它们,然后打印出数组(或段落)中每个字符串的总和。
The output for the test input should be:测试输入的输出应该是:
46 46
0 0
248 248
string json = YOUR_JSON_STRING;
string[] arrayStrings = json.Split("Label ");
List<int> lst = new List<int>();
foreach (string str in arrayStrings)
{
lst.Add(Convert.ToInt16(str.Substring(0, str.IndexOf("\"") - 1)));
}
//lst now contains all the numbers for you!
Keep coding!继续编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.