act*_*.se 4 c++ string parsing boost expression
我正在寻找一种干净的C++方法来解析包含$ {}中包含的表达式的字符串,并从编程计算表达式构建结果字符串.
示例:如果我实现程序让"user"评估为"foo"等,"来自$ {host}的Hi $ {user}"将被评估为"Hi foo from bar".
我正在考虑的当前方法包括一个状态机,它一次从字符串中吃掉一个字符,并在达到'}'后评估表达式.任何提示或其他建议?
注意:boost ::非常欢迎!:-)
更新感谢前三个建议!不幸的是我让这个例子太简单了!我需要能够检查$ {}内的内容,所以这不是一个简单的搜索和替换.也许它会说$ {uppercase:foo}然后我必须使用"foo"作为hashmap中的一个键,然后将其转换为大写,但我在编写上面的原始问题时试图避免$ {}的内部细节...... :-)
小智 5
#include <iostream>
#include <conio.h>
#include <string>
#include <map>
using namespace std;
struct Token
{
enum E
{
Replace,
Literal,
Eos
};
};
class ParseExp
{
private:
enum State
{
State_Begin,
State_Literal,
State_StartRep,
State_RepWord,
State_EndRep
};
string m_str;
int m_char;
unsigned int m_length;
string m_lexme;
Token::E m_token;
State m_state;
public:
void Parse(const string& str)
{
m_char = 0;
m_str = str;
m_length = str.size();
}
Token::E NextToken()
{
if (m_char >= m_length)
m_token = Token::Eos;
m_lexme = "";
m_state = State_Begin;
bool stop = false;
while (m_char <= m_length && !stop)
{
char ch = m_str[m_char++];
switch (m_state)
{
case State_Begin:
if (ch == '$')
{
m_state = State_StartRep;
m_token = Token::Replace;
continue;
}
else
{
m_state = State_Literal;
m_token = Token::Literal;
}
break;
case State_StartRep:
if (ch == '{')
{
m_state = State_RepWord;
continue;
}
else
continue;
break;
case State_RepWord:
if (ch == '}')
{
stop = true;
continue;
}
break;
case State_Literal:
if (ch == '$')
{
stop = true;
m_char--;
continue;
}
}
m_lexme += ch;
}
return m_token;
}
const string& Lexme() const
{
return m_lexme;
}
Token::E Token() const
{
return m_token;
}
};
string DoReplace(const string& str, const map<string, string>& dict)
{
ParseExp exp;
exp.Parse(str);
string ret = "";
while (exp.NextToken() != Token::Eos)
{
if (exp.Token() == Token::Literal)
ret += exp.Lexme();
else
{
map<string, string>::const_iterator iter = dict.find(exp.Lexme());
if (iter != dict.end())
ret += (*iter).second;
else
ret += "undefined(" + exp.Lexme() + ")";
}
}
return ret;
}
int main()
{
map<string, string> words;
words["hello"] = "hey";
words["test"] = "bla";
cout << DoReplace("${hello} world ${test} ${undef}", words);
_getch();
}
Run Code Online (Sandbox Code Playgroud)
我很乐意解释有关此代码的任何信息:)
| 归档时间: |
|
| 查看次数: |
1875 次 |
| 最近记录: |