使用回调和RegEx方法将JavaScript代码转换为c#中的等效代码
本文关键字:代码 转换 JavaScript 回调 RegEx 方法 | 更新日期: 2023-09-27 18:16:43
我有下面的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, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^''s]+)';
})
.replace(splatParam, '(.*?)')
.replace(optionalRegex, '''s*$1?''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#中的一些功能和工具的指导,可以帮助我编写类似于上面的东西。
关于我尝试做什么的更多细节,实际上我有一个表单,用户通过使用html5语音API输入他的命令,API将此语音转换为文本,然后将此文本提交给我的应用程序,我的应用程序工作从查看此文本开始,试图使用ReqEx找到所需的命令,然后执行与此输入命令映射的编程函数/回调。
我找到了解决方案,在using System.Collections.Generic;
使用Dictionary
,在using System.Text.RegularExpressions;
使用RegEx
,并需要在using System.Linq;
使用FirstOrDefault
功能
我使用Action
而不是函数Func
,因为在我的情况下回调是不返回任何东西,即它们是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()
{
}
}
}