【问题标题】:Lexer in C#(for procedure Pascal) That Uses Regular Expressions使用正则表达式的 C# 中的词法分析器(用于过程 Pascal)
【发布时间】:2018-10-03 20:31:30
【问题描述】:

帮助验证 Pascal 语言输入过程的正确性。请。

标识符、双引号括起来的字符串常量和单引号括起来的单个字符都可以作为参数。

是的

proc1('s',13,"sss");
proc2('s',s,d,11,"sss");
proc3("sss");

错误

proc1(s',11,"sss"); 
proc2('s',s,d,11,sss");
proc3("sss);
proc4("sss";

我可怜的尝试:

public void ThreadPoolCallback(Object threadContext)
    {
        if ((str.Length == 0) && (str[str.Length - 1] != ')'))
        {
            haveError = true;
        }
        else
        {
            int startIndex = str.IndexOf('('),
            lastIndex = str.LastIndexOf(')'),
            startIndex2 = str.LastIndexOf('('),
            lastIndex2 = str.IndexOf(')');
            if (startIndex < lastIndex && startIndex > 0 && lastIndex == str.Length - 1 &&
            startIndex == startIndex2 && lastIndex == lastIndex2)
            {
                int curr = startIndex + 1;
                while (curr < lastIndex)
                {
                    string s = "";
                    while (str[curr] != ',' && curr < lastIndex)
                    {
                        s += str[curr];
                        curr++;
                    }

                    curr++;
                }
            }
            else
            {
                haveError = true;
            }
        }
        doneEvent.Set();
    }

【问题讨论】:

  • 您的str 变量是否包含proc 和一个数字?
  • 对不起。我不明白你的

标签: c# regex lexer


【解决方案1】:

我还没有将整个 Pascal 引擎构建到这个正则表达式中,但它应该可以满足您的需求:

@"\((?:(?:'[\d\w_]+'|""[\d\w_]*""|[\d\w_]+),?)*\);"

它将从开头的括号“(”匹配由单引号或双引号括起的数字和字母(匹配对)或字母和数字后跟可选的逗号“,”并以括号“@”结尾987654324@' 和分号 ';'。

使用方法:

string test = "proc1('s',13,"sss");\n" + "proc2('s',s,d,11,"sss");\n"
+ "proc3("sss");" + "proc1(s',11,"sss");" + "proc2('s',s,d,11,sss");"
+ "proc3("sss);" + "proc4("sss";";

Regex regex = new Regex(@"\((?:(?:'[\d\w_]+'|""[\d\w_]*""|[\d\w_]+),?)*\);");

foreach (Match match in regex.Matches(test))
{
    Console.Write(match.Value);
}

【讨论】:

  • 非常感谢。对不起,我不能提高你的声誉,而不是大量的积分。
  • 呵呵,没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多