乐兴/令牌化分隔字符串

问题描述

我正在为一种小语言编写一个手写词法器,但是有一个奇怪的要求,即我不确定如何处理。

我需要能够支持定界字符串的概念,其中定界符可以是任何char。例如。字符串最有可能用双引号分隔(例如"hello"),但也很容易是/hello/,hello,

例如一些示例输入行可能是:

x = /abc/
y = "abc" +,def,z = zabcz

最后一种情况有点病态,但在技术上是可能的。

我正在尝试确定在一般情况下在分词化阶段是否有任何方法可以做到这一点?任何想法或建议都是宏大的。

解决方法

这是c ++和js中的解决方案。

c ++

#include "vector"
#include "string"
#include "iostream"
using namespace std;
// Lexically Analyze method
auto lex_argument(string code){
// Define variables
size_t equal_location;
int counter = 0;
auto variable;
string variable_name;
auto variable_info[2]
string code_for_inspection;
/* In the case of a variable,these two characters will hold the beginning and end of the string */
char string_variable_characters[2];
equal_location = code.find("=",code.length());
variable_value = code.substr(equal_location + 2,code.length());
variable_name = code.substr(code.begin(),equal_location - 2);
variable_info[0] = variable_name;
string_variable_characters[0] = (char) variable_value.substr(0,1);
string_variable_characters[1] = (char) 
variable_value.substr(variable_value.length() - 1,variable_value.length());
if(string_variable_charecters[0] = string_variable_charecters[1]){
variable_name.erase(0,1);
variable_value.erase(variable_value.length() - 1,variable_value.length());
variable_info[1] = variable_value;
}
return variable_info;
}

和js:

function lex_argument(code){
var equalLocation = code.search("=");
var variableInfo = [null,null];
variableInfo[1] = code.substr(1,equalLocation - 2);
variableInfo[0] = code.substr(equalLocation,code.length);
string_delimeters = [variableInfo[0].substr(1,2),variableInfo[0].substr(variableInfo[0].length - 1,variableInfo[0].length];
return variableInfo;
}