简体   繁体   English

从C#中的字符串中提取值

[英]Extracting values from a string in C#

I have the following string which i would like to retrieve some values from: 我有以下字符串,我想从中检索一些值:

============================
Control 127232:
map #;-
============================
Control 127235:
map $;NULL
============================
Control 127236:

I want to take only the Control . 我只想控制。 Hence is there a way to retrieve from that string above into an array containing like [127232, 127235, 127236] ? 因此,有没有一种方法可以从上面的字符串中检索出一个包含[127232, 127235, 127236]这样的数组?

One way of achieving this is with regular expressions, which does introduce some complexity but will give the answer you want with a little LINQ for good measure. 实现此目标的一种方法是使用正则表达式,它确实引入了一些复杂性,但会通过一些LINQ给出您想要的答案,以达到很好的效果。

Start with a regular expression to capture, within a group, the data you want: 从正则表达式开始,以便在组内捕获所需的数据:

var regex = new Regex(@"Control\s+(\d+):");

This will look for the literal string "Control" followed by one or more whitespace characters, followed by one or more numbers (within a capture group) followed by a literal string ":". 这将查找文字字符串“ Control”,后跟一个或多个空格字符,后跟一个或多个数字(在捕获组中),后跟文字字符串“:”。

Then capture matches from your input using the regular expression defined above: 然后使用上面定义的正则表达式从输入中捕获匹配项:

var matches = regex.Matches(inputString);

Then, using a bit of LINQ you can turn this to an array 然后,使用一些LINQ,您可以将其转换为数组

var arr = matches.OfType<Match>()
                 .Select(m => long.Parse(m.Groups[1].Value))
                 .ToArray();

now arr is an array of long 's containing just the numbers. 现在arr是一个long数组,其中仅包含数字。

Live example here: http://rextester.com/rundotnet?code=ZCMH97137 此处的实时示例: http : //rextester.com/rundotnet?code=ZCMH97137

try this (assuming your string is named s and each line is made with \\n): 试试看(假设您的字符串名为s,并且每行都用\\ n表示):

List<string> ret = new List<string>();
foreach (string t in s.Split('\n').Where(p => p.StartsWith("Control")))
    ret.Add(t.Replace("Control ", "").Replace(":", ""));

ret.Add(...) part is not elegant, but works... ret.Add(...)部分并不优雅,但是可以工作...

EDITED: 编辑:
If you want an array use string[] arr = ret.ToArray(); 如果要使用数组,请使用string[] arr = ret.ToArray();

SYNOPSYS: SYNOPSYS:
I see you're really a newbie, so I try to explain: 我发现您确实是一个新手,所以我尝试解释一下:

  • s.Split('\\n') creates a string[] (every line in your string) s.Split('\\n')创建一个字符串[](字符串中的每一行)
  • .Where(...) part extracts from the array only strings starting with Control .Where(...)部分仅从数组中提取以Control开头的字符串
  • foreach part navigates through returned array taking one string at a time foreach部分通过返回的数组导航,一次获取一个字符串
  • t.Replace(..) cuts unwanted string out t.Replace(..)切掉不需要的字符串
  • ret.Add(...) finally adds searched items into returning list ret.Add(...)最终将搜索到的项目添加到返回列表中

Off the top of my head try this (it's quick and dirty), assuming the text you want to search is in the variable 'text': 假设您要搜索的文本位于变量'text'中,请试着这样做(它又快又脏):

        List<string> numbers = System.Text.RegularExpressions.Regex.Split(text, "[^\\d+]").ToList();
        numbers.RemoveAll(item => item == "");   

The first line splits out all the numbers into separate items in a list, it also splits out lots of empty strings, the second line removes the empty strings leaving you with a list of the three numbers. 第一行将所有数字拆分为一个列表中的单独项目,它还拆分了许多空字符串,第二行删除了空字符串,为您提供了三个数字的列表。 if you want to convert that back to an array just add the following line to the end: 如果要将其转换回数组,只需将以下行添加到末尾:

        var numberArray = numbers.ToArray();

Yes, the way exists. 是的,方法存在。 I can't recall a simple way for It, but string is to be parsed for extracting this values. 我记不起它的简单方法,但是要解析字符串以提取此值。 Algorithm of it is next: 接下来是它的算法:

  1. Find a word "Control" in string and its end 在字符串中找到单词“ Control”及其结尾
  2. Find a group of digits after the word 在单词后面找到一组数字
  3. Extract number by int.parse or TryParse 通过int.parse或TryParse提取数字
  4. If not the end of the string - goto to step one 如果不是字符串的结尾-转到步骤1

realizing of this algorithm is almost primitive..) 该算法的实现几乎是原始的。.)

This is simplest implementation (your string is str): 这是最简单的实现(您的字符串为str):

    int i, number, index = 0;        
    while ((index = str.IndexOf(':', index)) != -1)
    {
        i = index - 1;
        while (i >= 0 && char.IsDigit(str[i])) i--;
        if (++i < index)
        {
            number = int.Parse(str.Substring(i, index - i));
            Console.WriteLine("Number: " + number);
        }
        index ++;
    }

Using LINQ for such a little operation is doubtful. 使用LINQ进行这样的小操作令人怀疑。

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

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