简体   繁体   English

c# 中变量声明和初始化的正则表达式

[英]Regex for variable declaration and initialization in c#

I want to write a RegEx to pull out all the variable values and their names from the variable declaration statement.我想编写一个正则表达式来从变量声明语句中提取所有变量值及其名称。 Say i have说我有

int i,k = 10,l=0整数 i,k = 10,l=0

i want to write a regex something like int\s^,?|(^,?)* but this will also accept k = 10 ie (without int preceding it) Basically idea is If string starts with int then get the variable list seperated by,我想写一个像 int\s^,?|(^,?)* 这样的正则表达式,但这也将接受 k = 10 即(前面没有 int)基本上的想法是如果字符串以 int 开头,那么将变量列表分开经过,

i know to extract csv values, but here my string has some initial value as well.我知道要提取 csv 值,但这里我的字符串也有一些初始值。 How can i resolve it?我该如何解决?

Start thinking about the structure of a definition, say,开始考虑定义的结构,比如说,

(a line can start with some spaces) followed by,

(Type) followed by

(at least one space)
(variable_1)
(optionally
   (comma // next var
    |
    '='number // initialization
    ) ...`

then try to convert each group:然后尝试转换每个组:

^      \s*    \w+           \s+        \w+         ?          (','    |  '=' \d+   ) ...
line  some    type          at least  var          optionally   more  or init some
start spaces  (some chars)  one space (some chars)              vars     val  digits

Left as homework to remove spaces and fix up the final regex.作为作业留下来删除空格并修复最终的正则表达式。

Here is some useful information which you can use以下是一些您可以使用的有用信息

http://compsci.ca/v3/viewtopic.php?t=6712 http://compsci.ca/v3/viewtopic.php?t=6712

Try this:尝试这个:

 ^(int|[sS]tring)\s+\w+\s*(=\s*[^,]+)?(,\s*\w+\s*(=\s*[^,]+)?)*$

It'll match your example code它将与您的示例代码匹配

int i,k = 10,l=0

And making a few assumptions about the language you may or may not be using, it'll also match:并对您可能使用或未使用的语言进行一些假设,它也会匹配:

int i, j, k=10, l=0
string i=23, j, k=10, l=0

You could build up your regular expression from the [C# Grammar]( http://msdn.microsoft.com/en-us/library/aa664812(VS.71).aspx) .您可以从 [C# Grammar]( http://msdn.microsoft.com/en-us/library/aa664812(VS.71).aspx)构建正则表达式。 But building a parser would certainly be better.但是构建一个解析器肯定会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM