0

I need to extract a substring from a given string using regex.

I am parsing c# code, and I need to get the variable which is checked for null value.

Note: I save the c# code in a text file and read the lines as string value

My string could be in following format.

string code = "if (!(strOld_Value == "" && strNew_Value == "") || (strOld_Value == "" && strNew_Value.ToLower() != "") ";

From the above input string, I need to extarct the variable names, that are checked for null values. i.e) my desired output should be

strOld_Value == "" strNew_Value == "" strOld_Value == "" strNew_Value.ToLower() != ""

It is not necessary that my string will always in the same pattern, sometimes my string can be a simple one as follows,

string code = "if (Name == "")"

In the above case, my desired output is, Name == ""

Is it possible to write a generic regex pattern for this scenario? Thanks in Advance.

2
  • 1
    Sounds to me like you need to use/write a lexer/parser. Regex alone probably won't cut it here. Commented May 8, 2018 at 10:54
  • You can use Roslyn to get the AST of your code snippet and search for comparison operators: github.com/dotnet/roslyn/wiki/… Commented May 8, 2018 at 11:13

3 Answers 3

1

You can use the following regex pattern:

[_0-9a-zA-Z\s\.]+[()\s]*(==|!=)\s*\"[0-9a-zA-Z]*\"
Sign up to request clarification or add additional context in comments.

2 Comments

It fails for e.g. if (var1 == "")
Include 0-9 in the variable name [_0-9a-zA-Z\s\.]+[()\s]*(==|!=)\s*\"[0-9a-zA-Z]*\"
1

As spender suggests, sounds like you need the ability to parse C# code and access the names of the variables identified by the parser

See S.O. How to programmatically parse and modify C# code

Comments

1

You can try this regex:

(\w+(\.\w+[\)\(]*)*\s*(==|\!=)\s*\"\")
  • [\w]+ - matches any word character one or more times
  • (\.\w+[\)\(]*)* = (matches . and any word character after it, and there can be parentheses) zero or more times
  • \s* - optional space
  • (==|\!=) - == or !=
  • \s* - optional space
  • \"\" - matches empty value ("")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.