Answer the question
In order to leave comments, you need to log in
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
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]+?)['""]?)?;");
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());
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question