I
I
Igor2013-12-22 23:48:58
Regular Expressions
Igor, 2013-12-22 23:48:58

Regex C#. How to extract values ​​from text?

We have a richTextBox with text (any c++/c# code). It is necessary to pull out the declaration of variables from it in the dataGridView. It is necessary to find matches of the form variable_type variable_name = variable_value; or variable_type variable_name; and split into 3 or 2 parts in order, respectively, to enter dataGridView into 3 columns. Help, please, with writing regular expressions.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dima_horror, 2013-12-23
@ReLogan

Matches mm = Regex.Matches(input, @"(byte|sbyte|short|ushort|int|uint|long|ulong|float|double|decimal|char|string|bool|object|var)\s+([a-zA-Zа-яА-Я]{1}[^\s;]*)(\s+=\s+['""]?([\s\S]+?)['""]?)?;");

Try...

I
Ilya Glebov, 2013-12-24
@IljaGlebov

For C# a good option is Roslyn

class Program {
   static void Main(string[] args) {
            	
   SyntaxTree tree = SyntaxTree.ParseText(
            @"using System;
 
             namespace HelloWorld    {
               class Program  {
                 static void Main(string[] args)  {
                    var i = 10 * 20;
                    String s = t.ToString();
                    }
                 }
              }");
  var comp = Compilation.Create("HelloWorld")
     .AddReferences(MetadataReference.CreateAssemblyReference("mscorlib"))
     .AddSyntaxTrees(tree);
            
  var model = comp.GetSemanticModel(tree);

  new Walker(model).Visit(tree.GetRoot());

  Console.ReadKey();
}

class Walker : SyntaxWalker {
   private readonly SemanticModel model;

   public Walker(SemanticModel model) : base() {
     this.model = model;
    }

    public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) {
      var declaredSymbol = (LocalSymbol) model.GetDeclaredSymbol(node);
      Console.WriteLine("{0} {1} {2}", declaredSymbol.Type, declaredSymbol.Name,         node.Initializer.GetText());
   }
 }

E
Eugene, 2013-12-23
@pushthebutton

Hmm, post the whole list. That is, bring a piece of what needs to be parsed.
Perhaps you are digging in the wrong direction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question