【发布时间】:2016-03-24 20:48:57
【问题描述】:
这是一个使用自定义正则表达式实现字典的程序,它标记所有输入的字符串。现在我希望与任何正则表达式不匹配的字符串必须以“不在语法中”行显示。我找不到任何类型的解决方案。
static void Main(string[] args)
{
string StringRegex = "\"(?:[^\"\\\\]|\\\\.)*\"";
string IntegerRegex = @"[0-9]+";
string CommentRegex = @"//.*|/\*[\s\S]*\*/";
string KeywordRegex = @"\b(?:astart|ainput|atake|aloop|batcommand|batshow|batprint|batmult|batadd|batsub|batdiv|batif|batelse|batgo|batend|till|and)\b";
string DataTypeRegex = @"\b(?:int|string)\b";
string IdentifierRegex = @"[a-zA-Z]";
string ParenthesisRegex = @"\(|\)";
string BracesRegex = @"\{|\}";
string ArrayBracketRegex = @"\[|\]";
string PuncuationRegex = @"\;|\:|\,|\.";
string RelationalExpressionRegex = @"\>|\<|\==";
string ArthimeticOperatorRegex = @"\+|\-|\*|\/";
string WhitespaceRegex = @" ";
Dictionary<string, string> Regexes = new Dictionary<string, string>()
{
{"String", StringRegex},
{"Integer", IntegerRegex },
{"Comment", CommentRegex},
{"Keyword", KeywordRegex},
{"Datatype", DataTypeRegex },
{"Identifier", IdentifierRegex },
{"Parenthesis", ParenthesisRegex },
{"Brace", BracesRegex },
{"Square Bracket", ArrayBracketRegex },
{"Puncuation Mark", PuncuationRegex },
{"Relational Expression", RelationalExpressionRegex },
{"Arithmetic Operator", ArthimeticOperatorRegex },
{"Whitespace", WhitespaceRegex }
};
string input;
input = Convert.ToString(Console.ReadLine());
var matches = Regexes.SelectMany(a => Regex.Matches(input, a.Value)
.Cast<Match>()
.Select(b =>
new
{
Value = b.Value + "\n",
Index = b.Index,
Token= a.Key
}))
.OrderBy(a => a.Index).ToList();
for (int i = 0; i < matches.Count; i++)
{
if (i + 1 < matches.Count)
{
int firstEndPos = (matches[i].Index + matches[i].Value.Length);
if (firstEndPos > matches[(i + 1)].Index)
{
matches.RemoveAt(i + 1);
i--;
}
}
}
foreach (var match in matches)
{
Console.WriteLine(match);
}
Console.ReadLine();
}
【问题讨论】:
-
如果没有一个正则表达式匹配,是
var matchesnull还是空? -
不,如果我输入 asdasdas 那么单个字符会被标记并显示为标识符,但我希望它显示为“非语言”之类的错误
-
但在这种情况下,
asdasdas匹配正则表达式之一 (IdentifierRegex = @"[a-zA-Z]"),这是预期的行为。请澄清。 -
标识符是单个字符,例如 a、b、c... 但是当我输入 asdasdas 时,它不会将其视为一个完整的字符串,而是显示 a= identifier, s=identifier, d=标识符等,表示它拆分字符串并一次显示一个字符。我希望它将 asdasdas 作为一个字符串并显示 NOT IN GRAMMAR。
-
然后正则表达式应更改为
IdentifierRegex = @"\b[a-zA-Z]\b";,然后asdasdas将不匹配,您将能够测试是否为空。检查this IDEONE demo