我正在编写一个文本解析器,它需要能够从行中删除注释。我使用的是一种相当简单的语言,其中所有注释都由 # 字符启动,之后删除所有内容会很简单,但我必须处理 # 在字符串内部的可能性。
因此,我的问题是,给定一个字符串,例如
Value="字符串#1";"字符串#2"; # 这是一个由 "-delimited strings, "Like this"
我怎样才能最好地提取子字符串
Value="String#1";"String#2";
(注意尾随空格)
请注意,注释可能包含引号,而且整行可能会选择 "和 ' 分隔符,尽管它会在整行中保持一致。如果它很重要,这是事先知道的。字符串中的引号将被\
转义最佳答案
std::string stripComment(std::string str) {
bool escaped = false;
bool inSingleQuote = false;
bool inDoubleQuote = false;
for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
if(escaped) {
escaped = false;
} else if(*it == '\\' && (inSingleQuote || inDoubleQuote)) {
escaped = true;
} else if(inSingleQuote) {
if(*it == '\'') {
inSingleQuote = false;
}
} else if(inDoubleQuote) {
if(*it == '"') {
inDoubleQuote = false;
}
} else if(*it == '\'') {
inSingleQuote = true;
} else if(*it == '"') {
inDoubleQuote = true;
} else if(*it == '#') {
return std::string(str.begin(), it);
}
}
return str;
}
编辑:或者更教科书的 FSM,
std::string stripComment(std::string str) {
int states[5][4] = {
// \ ' "
{0, 0, 1, 2,}
{1, 3, 0, 1,}, //single quoted string
{2, 4, 2, 0,}, //double quoted string
{1, 1, 1, 1,}, //escape in single quoted string
{2, 2, 2, 2,}, //escape in double quoted string
};
int state = 0;
for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
switch(*it) {
case '\\':
state = states[state][1];
break;
case '\'':
state = states[state][2];
break;
case '"':
state = states[state][3];
break;
case '#':
if(!state) {
return std::string(str.begin(), it);
}
default:
state = states[state][0];
}
}
return str;
}
states
数组定义了 FSM 状态之间的转换。
第一个索引是当前状态,0
,1
,2
,3
,或者4
。
第二个索引对应字符,\
、'
、"
,或者其他字符。
根据当前状态和字符,数组告诉下一个状态。
仅供引用,这些假定反斜杠转义字符串中的任何字符。您至少需要它们来转义反斜杠,这样您就可以拥有一个以反斜杠结尾的字符串。
关于c++ - 从字符串中删除行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626009/