Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.RegularExpressions;
- namespace Simple
- {
- class Program
- {
- #region valid
- static string validString = "" +
- "//Conmet[[[\n" +
- "/*" +
- "asd[]]]]" +
- "*/" +
- "int a = 0;" +
- "int b = 10;" +
- "while(a+b<100){" +
- "a++;" +
- "str = \"asd\"" +
- "};";
- #endregion
- #region not valid
- static string notValidString = "" +
- "int a = {0;" +
- "(int b = 10;" +
- "while}(a+b<100){" +
- "a++;)" +
- "};";
- #endregion
- static void Main(string[] args)
- {
- List<string> strings = new List<string>() { validString, notValidString, "{[(])}", "}", "'][{}]]'", "//my name is [asd[}\n"};
- foreach (var str in strings)
- {
- Console.WriteLine($"string is { CheckValid(str)}");
- }
- }
- public static readonly string[] symbs = { "{", "[","(","\"","'","}","]",")"};
- private static bool CheckValid(string str){
- if (str == null)
- throw new ArgumentException("String is null");
- var s = Regex.Matches(str, "[\\(\\{\\[\\]\\}\\)'\"\n]|(?:[\\/\\*].)|([\\/\\/].)/g").ToArray();
- List<string> lex = new List<string>();
- foreach(var a in s)
- {
- lex.Add(a.Value);
- }
- Stack<string> opens = new Stack<string>();
- foreach(var c in lex){
- if(opens.Count>0)
- {
- if (opens.Peek() == "//" && c != "\n")
- continue;
- if (opens.Peek() == "/*" && c != "*/")
- continue;
- }
- switch(c){
- case "{":
- case "[":
- case "(":
- case @"//":
- case @"/*":
- opens.Push(c);
- continue;
- case "'":
- case "\"":
- if (opens.Count == 0 || opens.Peek() != c){
- opens.Push(c);
- continue;}
- break;
- }
- //Закрывающие
- if (opens.Count == 0)
- return false;
- if (opens.Peek() == "'" && c != "'")
- continue;
- if (opens.Peek() == "\"" && c != "\"")
- continue;
- switch (c){
- case "}":
- if (opens.Peek() == "{")
- opens.Pop();
- break;
- case "]":
- if (opens.Peek() == "[")
- opens.Pop();
- break;
- case ")":
- if (opens.Peek() == "(")
- opens.Pop();
- break;
- case "\"":
- if (opens.Peek() == "\"")
- opens.Pop();
- break;
- case "'":
- if (opens.Peek() == "'")
- opens.Pop();
- break;
- case "\n":
- if (opens.Peek() == "//")
- opens.Pop();
- break;
- case "*/":
- if (opens.Peek() == "/*")
- opens.Pop();
- break;}}
- return !opens.Any();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement