检查字符串的语法 - C#

Checking syntax of strings - C#

我正在尝试了解如何在 C# 中分析句子的语法。 在我的例子中,我有一个语法,每个句子都必须遵循。 语法如下所示:

A 'B' is a 'C'.

每个句子必须包含五个单词。我的句子的第一个词必须是 'A',第三个 'is' 和第四个 'a'.

现在我想检查一个测试句子是否符合我的语法。

测试句:

A Dog is no Cat.

在这个例子中,测试句子是错误的,因为第四个词是 'no' 而不是 'a' 根据语法应该是什么。

我了解了 LINQ,我可以在其中查询包含一组指定单词的句子。

代码看起来像这样:

//Notice the third sentence would have the correct syntax
string text = "A Dog is no Cat. My Dog is a Cat. A Dog is a Cat.";

//Splitting text into single sentences
string[] sentences = text.Split(new char[] { '.'});

//Defining the search terms
string[] wordToMatch ={"A", "is"};

//Find sentences that contain all terms I'm looking for
var sentenceQuery = from sentence in sentences
        let w = sentence.Split(new Char[] {'.'})
        where w.Distinct().Intersect(wordsToMatch).Count == wordsToMatch.Count()
        select sentence;

使用这段代码,我可以检查句子是否包含我要查找的术语,但问题是它没有检查单词在句子中的位置。 有没有办法我也可以检查位置,或者有更好的方法来使用 C# 检查句子的语法?

尝试使用正则表达式,像这样:

using System.Text.RegularExpressions;

...

string source = "A Dog is no Cat.";

bool result = Regex.IsMatch(source, @"^A\s+[A-Za-z0-9]+\s+is\s+a\s+[A-Za-z0-9]+\.$");  

图案说明:

 ^           - start of the string (anchor)
 A           - Letter A 
\s+          - one or more whitelines (spaces)
[A-Za-z0-9]+ - 1st word (can contain A..Z, a..z letters and 0..9 digits)
\s+          - one or more whitelines (spaces) 
 is          - is 
\s+          - one or more whitelines (spaces) 
 a           - a
\s+          - one or more whitelines (spaces)
[A-Za-z0-9]+ - 2nd word (can contain A..Z, a..z letters and 0..9 digits)
\.           - full stop 
 $           - end of the string (anchor)

您可以稍微修改代码并获取实际的第 1 和第 2 个字符串的值:

string source = "A Dog is a Cat."; // valid string

string pattern =
   @"^A\s+(?<First>[A-Za-z0-9]+)\s+is\s+a\s+(?<Second>[A-Za-z0-9]+)\.$";

var match = Regex.Match(source, pattern); 

if (match.Success) {
  string first = match.Groups["First"].Value;   // "Dog"
  string second = match.Groups["Second"].Value; // "Cat"

  ... 
}  

正则表达式适用于此,并且是最简洁的,但可能不是最易读的解决方案。这是一个简单的方法,如果句子有效,它将 return 为真:

private bool IsSentenceValid(string sentence)
{
    // split the sentence into an array of words
    char[] splitOn = new char[] {' '};
    string[] words = sentence.ToLower().Split(splitOn); // make all chars lowercase for easy comparison

    // check for 5 words.
    if (words.Length != 5)
        return false;

    // check for required words
    if (words[0] != "a" || words[2] != "is" || words[3] != "a")
        return false;

    // if we got here, we're fine!
    return true;
}

只想抛砖引玉。我会为此写三个 classes:

  1. SentenceManager:获取字符串作为句子,有public方法public string GetWord(word_index)。例如 GetWord(3) 将 return 给出给 class 构造函数的句子中的第三个词。

  2. SentenceSyntax:在这个class中,你可以说出你的句子必须有多少个单词。必须知道哪些单词,您也可以设置这些单词的索引。

  3. SyntaxChecker:这个 class 得到一个 SentenceSyntax 对象和一个 SentenceManager 对象,并且有一个名为 Check 的函数 return如果语法与句子匹配则为真。

请记住,有成千上万种方法可以让某事发挥作用。但是有一些方法可以正确地做到这一点。

你绝对应该使用 Regex 或类似

的东西来做到这一点

只是为了好玩,我想按照你的方式去做。如果我发疯了,我会这样做 :)

//Notice the third sentence would have the correct syntax
string text = "A Dog is no Cat.My Dog is a Cat.A Dog is a Cat.";

//Splitting text into single sentences
string[] sentences = text.Split(new char[] { '.' });

string[] wordsToMatch = { "A", "*", "is", "a", "*" };

var sentenceQuery = from sentence in sentences
                    let words = sentence.Split(' ')
                    where words.Length == wordsToMatch.Length && 
                          wordsToMatch.Zip(words, (f, s) => f == "*" || f == s).All(p => p)
                    select sentence;

使用此代码,您还可以获得灵活性,例如不区分大小写的比较,trim space 围绕单词等 - 当然您必须为此编写代码