解析空格分隔文本的最佳方法

时间:2020-03-05 18:50:56  来源:igfitidea点击:

我有这样的字符串

/c SomeText\MoreText "Some Text\More Text\Lol" SomeText

我想标记化它,但是我不能只在空格上分开。我想出了一个比较丑陋的解析器,但我想知道是否有人设计得更优雅。

这是在Cbtw。

编辑:我的丑陋版本虽然丑陋,却是O(N),实际上可能比使用RegEx更快。

private string[] tokenize(string input)
{
    string[] tokens = input.Split(' ');
    List<String> output = new List<String>();

    for (int i = 0; i < tokens.Length; i++)
    {
        if (tokens[i].StartsWith("\""))
        {
            string temp = tokens[i];
            int k = 0;
            for (k = i + 1; k < tokens.Length; k++)
            {
                if (tokens[k].EndsWith("\""))
                {
                    temp += " " + tokens[k];
                    break;
                }
                else
                {
                    temp += " " + tokens[k];
                }
            }
            output.Add(temp);
            i = k + 1;
        }
        else
        {
            output.Add(tokens[i]);
        }
    }

    return output.ToArray();            
}

解决方案

回答

Microsoft.VisualBasic.FileIO命名空间(在Microsoft.VisualBasic.dll中)具有TextFieldParser,可用于在带空格的文本上拆分。它可以很好地处理引号内的字符串(即" this is one token" thisistokentwo)。

注意,仅因为DLL表示VisualBasic并不意味着我们只能在VB项目中使用它。它是整个框架的一部分。

回答

我们可能还需要研究正则表达式。那可能会帮到你。这是从MSDN窃取的示例...

using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }

    }

}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumped over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54

回答

Craig是正确使用的正则表达式。 Regex.Split可能会更简洁地满足需求。

回答

我们正在做什么的计算机术语是词法分析;请阅读该文章,以很好地总结此常见任务。

根据示例,我猜测我们希望空格分隔单词,但是引号中的内容应视为不带引号的"单词"。

最简单的方法是将一个单词定义为正则表达式:

([^"^\s]+)\s*|"([^"]+)"\s*

该表达式表示"单词"是(1)用空格包围的非引号,非空格文本,或者(2)用引号包围的非引号文本(后跟一些空格)。请注意使用捕获括号突出显示所需的文本。

有了该正则表达式,算法就很简单:在文本中搜索由捕获括号定义的下一个"单词",然后将其返回。重复该操作,直到用完"单词"为止。

这是我可以在VB.NET中想到的最简单的工作代码。请注意,由于有两组捕获括号,因此我们必须检查两组数据。

Dim token As String
Dim r As Regex = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")
Dim m As Match = r.Match("this is a ""test string""")

While m.Success
    token = m.Groups(1).ToString
    If token.length = 0 And m.Groups.Count > 1 Then
        token = m.Groups(2).ToString
    End If
    m = m.NextMatch
End While

注1:上面Will的答案与此想法相同。希望这个答案可以更好地解释幕后的细节:)

回答

[^\t]+\t|"[^"]+"\t

使用Regex肯定看起来是最好的选择,但是这只返回了整个字符串。我正在尝试进行调整,但到目前为止运气还不足。

string[] tokens = System.Text.RegularExpressions.Regex.Split(this.BuildArgs, @"[^\t]+\t|""[^""]+""\t");

回答

有状态机方法。

private enum State
    {
        None = 0,
        InTokin,
        InQuote
    }

    private static IEnumerable<string> Tokinize(string input)
    {
        input += ' '; // ensure we end on whitespace
        State state = State.None;
        State? next = null; // setting the next state implies that we have found a tokin
        StringBuilder sb = new StringBuilder();
        foreach (char c in input)
        {
            switch (state)
            {
                default:
                case State.None:
                    if (char.IsWhiteSpace(c))
                        continue;
                    else if (c == '"')
                    {
                        state = State.InQuote;
                        continue;
                    }
                    else
                        state = State.InTokin;
                    break;
                case State.InTokin:
                    if (char.IsWhiteSpace(c))
                        next = State.None;
                    else if (c == '"')
                        next = State.InQuote;
                    break;
                case State.InQuote:
                    if (c == '"')
                        next = State.None;
                    break;
            }
            if (next.HasValue)
            {
                yield return sb.ToString();
                sb = new StringBuilder();
                state = next.Value;
                next = null;
            }
            else
                sb.Append(c);
        }
    }

它可以很容易地扩展为嵌套引号和转义之类的东西。返回为" IEnumerable <string>"将使代码仅解析所需的内容。由于字符串是不可变的,因此这种惰性方法没有任何实际缺点,因此我们可以在解析整个过程之前就知道"输入"不会改变。

请参阅:http://en.wikipedia.org/wiki/基于Automata的编程