Home > OS >  How to use regex to find variable name beginning with @ in a string expression?
How to use regex to find variable name beginning with @ in a string expression?

Time:10-10

The programmer hope to get two variables day1 and day2 by using regex, all the other variables in string expression beginning with the character @ too.

The example of a string expression: @day1 - @day2 > 3

Thanks!

CodePudding user response:

You could use a lookbehind to get the variable names, like so:

var regex = new Regex("(?<=@)\\w ");

This will get the words preceded by an @ sign

CodePudding user response:

You can simply use positive lookahead here.

string = "@day1 - @day2 > 3";
Regex regex = new Regex("(?<=@)\\w ", RegexOptions.Compiled);
var match = regex.Matches(a);
foreach( var val in match )
{
   Console.WriteLine(val);
}

val contains the match values.

  • Related