有一种方法可以将数据值转换为正则表达式模式中定义的另一个值吗?
我的意思是,我想定义一个像a=1|b=2|c=3
.
因此,当我将a
值传递给 Regex 时,它会返回 me 1
。如果 b 返回2
... 等等。
这可能吗?
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]));
}
或者
string val = "a";
Int32.Parse(Regex.Match("a=1|b=2|c=3", val + @"=(\d)").Groups[1].Value);
您可以像这样在 C# 中执行此操作:
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
我使用了匹配的正则表达式[abc]
,a
或者b
根据c
匹配,内部使用的委托在Replace()
字典中查找匹配以决定用什么替换它。
您可以将 Regex.Replace 与委托一起使用来评估匹配项。
请参阅: http: //msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator (v=vs.110).aspx 和:http: //msdn.microsoft.com/en-us/库/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;
}
}