使用回调和 RegEx 方法将 JavaScript 代码转换为 C# 中的等效代码
Converting a JavaScript code using callbacks and RegEx method to equivalent code in C#
我有下面的 JavaScript 代码,它返回了一个与用户命令相关的函数回调,用户命令可以以不同的方式使用,因此需要 RegEx:
(function (undefined) {
"use strict";
var root = this;
var commandsList = [];
var debugStyle = 'font-weight: bold; color: #00f;';
// The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
var optionalParam = /\s*\((.*?)\)\s*/g;
var optionalRegex = /(\(\?:[^)]+\))\?/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\^$|#]/g;
var commandToRegExp = function(command) {
command = command.replace(escapeRegExp, '\$&')
.replace(optionalParam, '(?:)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\s]+)';
})
.replace(splatParam, '(.*?)')
.replace(optionalRegex, '\s*?\s*');
return new RegExp('^' + command + '$', 'i');
};
var registerCommand = function(command, cb, phrase) {
commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
root.console.log('Command successfully loaded: %c'+phrase, debugStyle);
};
root.fonixListen = {
addCommands: function(commands) {
var cb;
for (var phrase in commands) {
if (commands.hasOwnProperty(phrase)) {
cb = root[commands[phrase]] || commands[phrase];
if (typeof cb === 'function') {
// convert command to regex then register the command
registerCommand(commandToRegExp(phrase), cb, phrase);
} else if (typeof cb === 'object' && cb.regexp instanceof RegExp) {
// register the command
registerCommand(new RegExp(cb.regexp.source, 'i'), cb.callback, phrase);
}
}
}
},
executeCommand: function(commandText) {
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
// execute the matched command
commandsList[j].callback.apply(this, parameters);
return true;
}
}
}
};
}).call(this)
下面是一些命令:
var commands = {
'hello :name *term': function(name) {
alert('hello '+name+''); // i.e. consider *term as optional input
},
'items identification': {
'regexp': /^(What is|What's|Could you please tell me|Could you please give me) the meaning of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/,
'callback': itemsIdentification,
},
'ML SoH': {
'regexp': /^(What is|What's|Could you please tell me|Could you please give me) the (stock|inventory) of ML$/,
'callback': mlSOH,
},
'Report stock on hand': {
'regexp': /^(What is|What's) (our|the) (stock|inventory|SoH) of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/,
'callback': SoH,
},
'Basic Mathematical Opertions': {
// ?\s? can be used instead of space, also could use /i instead of $/,
'regexp': /^(What is|What's|Calculate|How much is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/,
'callback': math,
},
};
在运行应用程序中,执行addCommands
命令,并根据用户输入的命令,执行executeCommand
命令。
以上对我来说工作得很好,但我正在转向 C#,并且对它很陌生,所以寻求帮助,至少指导 C# 中的一些功能和工具可以帮助我编写类似的东西以上。
更新
关于我尝试做的更多细节,实际上我有一个表格,用户使用 HTL5 语音 API 通过语音输入他的命令,API 将这个语音转换成文本,然后我提交了这个文本到我的应用程序,我的应用程序工作从查看此文本开始,尝试使用 ReqEx 找到所需的命令,然后执行与此输入命令映射的编程 function/callback。
我找到了在 using System.Collections.Generic;
使用 Dictionary
并在 using System.Text.RegularExpressions;
使用 RegEx
的解决方案,同时需要一个名为 FirstOrDefault
的函数,在 using System.Linq;
我使用 Action
而不是函数 Func
因为在我的例子中回调没有 return 任何东西,即它们是 void
函数,并且因为没有输入参数提供,我用的是Action
-delegate,没有用Action<string[]>
。
工作代码是:
using System;
using System.Collections.Generic; // for Dictionary
using System.Linq; // for FirstOrDefault
using System.Text.RegularExpressions; // for RegEx
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var input = "What's the meaning of Stretch Hood";
var functions = new Dictionary<Regex, Action>
{
{new Regex("/^(What is|What's|Could you please tell me|Could you please give me) the meaning of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/"),
itemsIdentification},
{new Regex("/^(What is|What's|Could you please tell me|Could you please give me) the (stock|inventory) of ML$/"),
mlSOH},
{new Regex("/^(What is|What's) (our|the) (stock|inventory|SoH) of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/"),
SoH},
{new Regex("/^(What is|What's|Calculate|How much is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/"),
math},
};
functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value?.Invoke(); // This will execute the first Action found wherever the input matching the RegEx, the ?. means if not null ([Null-conditional Operators][1])
// or
Action action;
action = functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value;
if (action != null)
{
action.Invoke();
}
else
{
// No function with that name
}
}
public static void itemsIdentification()
{
Console.WriteLine("Fn 1");
}
public static void mlSOH()
{
Console.WriteLine("Fn 2");
}
public static void SoH()
{
}
public static void math()
{
}
}
}
我有下面的 JavaScript 代码,它返回了一个与用户命令相关的函数回调,用户命令可以以不同的方式使用,因此需要 RegEx:
(function (undefined) {
"use strict";
var root = this;
var commandsList = [];
var debugStyle = 'font-weight: bold; color: #00f;';
// The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
var optionalParam = /\s*\((.*?)\)\s*/g;
var optionalRegex = /(\(\?:[^)]+\))\?/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\^$|#]/g;
var commandToRegExp = function(command) {
command = command.replace(escapeRegExp, '\$&')
.replace(optionalParam, '(?:)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\s]+)';
})
.replace(splatParam, '(.*?)')
.replace(optionalRegex, '\s*?\s*');
return new RegExp('^' + command + '$', 'i');
};
var registerCommand = function(command, cb, phrase) {
commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
root.console.log('Command successfully loaded: %c'+phrase, debugStyle);
};
root.fonixListen = {
addCommands: function(commands) {
var cb;
for (var phrase in commands) {
if (commands.hasOwnProperty(phrase)) {
cb = root[commands[phrase]] || commands[phrase];
if (typeof cb === 'function') {
// convert command to regex then register the command
registerCommand(commandToRegExp(phrase), cb, phrase);
} else if (typeof cb === 'object' && cb.regexp instanceof RegExp) {
// register the command
registerCommand(new RegExp(cb.regexp.source, 'i'), cb.callback, phrase);
}
}
}
},
executeCommand: function(commandText) {
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
// execute the matched command
commandsList[j].callback.apply(this, parameters);
return true;
}
}
}
};
}).call(this)
下面是一些命令:
var commands = {
'hello :name *term': function(name) {
alert('hello '+name+''); // i.e. consider *term as optional input
},
'items identification': {
'regexp': /^(What is|What's|Could you please tell me|Could you please give me) the meaning of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/,
'callback': itemsIdentification,
},
'ML SoH': {
'regexp': /^(What is|What's|Could you please tell me|Could you please give me) the (stock|inventory) of ML$/,
'callback': mlSOH,
},
'Report stock on hand': {
'regexp': /^(What is|What's) (our|the) (stock|inventory|SoH) of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/,
'callback': SoH,
},
'Basic Mathematical Opertions': {
// ?\s? can be used instead of space, also could use /i instead of $/,
'regexp': /^(What is|What's|Calculate|How much is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/,
'callback': math,
},
};
在运行应用程序中,执行addCommands
命令,并根据用户输入的命令,执行executeCommand
命令。
以上对我来说工作得很好,但我正在转向 C#,并且对它很陌生,所以寻求帮助,至少指导 C# 中的一些功能和工具可以帮助我编写类似的东西以上。
更新 关于我尝试做的更多细节,实际上我有一个表格,用户使用 HTL5 语音 API 通过语音输入他的命令,API 将这个语音转换成文本,然后我提交了这个文本到我的应用程序,我的应用程序工作从查看此文本开始,尝试使用 ReqEx 找到所需的命令,然后执行与此输入命令映射的编程 function/callback。
我找到了在 using System.Collections.Generic;
使用 Dictionary
并在 using System.Text.RegularExpressions;
使用 RegEx
的解决方案,同时需要一个名为 FirstOrDefault
的函数,在 using System.Linq;
我使用 Action
而不是函数 Func
因为在我的例子中回调没有 return 任何东西,即它们是 void
函数,并且因为没有输入参数提供,我用的是Action
-delegate,没有用Action<string[]>
。
工作代码是:
using System;
using System.Collections.Generic; // for Dictionary
using System.Linq; // for FirstOrDefault
using System.Text.RegularExpressions; // for RegEx
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var input = "What's the meaning of Stretch Hood";
var functions = new Dictionary<Regex, Action>
{
{new Regex("/^(What is|What's|Could you please tell me|Could you please give me) the meaning of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/"),
itemsIdentification},
{new Regex("/^(What is|What's|Could you please tell me|Could you please give me) the (stock|inventory) of ML$/"),
mlSOH},
{new Regex("/^(What is|What's) (our|the) (stock|inventory|SoH) of (TF|FFS|SF|SHF|FF|Tube Film|Shrink Film|Stretch Hood|Stretch Hood Film|Flat Film)$/"),
SoH},
{new Regex("/^(What is|What's|Calculate|How much is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/"),
math},
};
functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value?.Invoke(); // This will execute the first Action found wherever the input matching the RegEx, the ?. means if not null ([Null-conditional Operators][1])
// or
Action action;
action = functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value;
if (action != null)
{
action.Invoke();
}
else
{
// No function with that name
}
}
public static void itemsIdentification()
{
Console.WriteLine("Fn 1");
}
public static void mlSOH()
{
Console.WriteLine("Fn 2");
}
public static void SoH()
{
}
public static void math()
{
}
}
}