There's a way to transform a data value into another defined in a regex pattern?
I mean, I want to define a pattern like a=1|b=2|c=3.
So when if I pass the a value to Regex it returns me 1. If b returns 2 ... etc.
It's that possible?
There's a way to transform a data value into another defined in a regex pattern?
I mean, I want to define a pattern like a=1|b=2|c=3.
So when if I pass the a value to Regex it returns me 1. If b returns 2 ... etc.
It's that possible?
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (Match m in Regex.Matches("a=1|b=2|c=3", @"\w?=\d?"))
{
string[] val = m.Value.Split('=');
dic.Add(val[0], Int32.Parse(val[1]));
}
Or
string val = "a";
Int32.Parse(Regex.Match("a=1|b=2|c=3", val + @"=(\d)").Groups[1].Value);
You can do this in C# like this:
var input = "a, b, c";
Dictionary<string, string> lookup = new Dictionary<string, string>()
{
{"a", "1"},
{"b", "2"},
{"c", "3"}
};
string result = Regex.Replace(input, "[abc]", m => lookup[m.Value] , RegexOptions.None);
Console.WriteLine(result); // outputs 1, 2, 3
I have used the regular expression [abc] which matches either a, b or c then depending on the match, the delegate used inside Replace() looks the match inside a dictionary to decide what to replace it with.
You could use Regex.Replace with a delegate to evaluate the matches.
See: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator(v=vs.110).aspx and: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=vs.110).aspx
The answer is NO. Regex only return match sucess/fail and that which matches the pattern.
You could however determine a group number match, and that may enable you to translate
that into a value or whatever you want.
But be sure the power of regex is really needed for the job, and not just a simple string compare.
Otherwise you could build a custom trie.
Pseudo code:
pattern = @"
( Enie ) # (1)
| ( Menie ) # (2)
| ( Minie ) # (3)
| ( Moe ) # (4)
";
int GetValue( string& str )
{
smatch match;
if ( regex_find ( pattern, str, match, flags.expanded ) )
{
if ( match[1].matched )
return val1;
if ( match[2].matched )
return val2;
if ( match[3].matched )
return val3;
if ( match[4].matched )
return val4;
}
}