【发布时间】:2017-12-05 04:35:23
【问题描述】:
我想修改给定的正则表达式以生成以下匹配列表。我很难用语言描述这个问题。
我想使用正则表达式来匹配一组“令牌”。具体来说,我希望匹配&&,||,;,(,),并且任何不包含这些字符的字符串都应该是匹配的。
我遇到的问题是区分一根管子和两根管子。我怎样才能产生所需的匹配?非常感谢您的帮助!
表达式:
((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)
测试字符串
a < b | c | d > e >> f && ((g) || h) ; i
预期匹配
a < b | c | d > e >> f
&&
(
(
g
)
||
h
)
;
i
实际匹配
a < b
|
c
|
d > e >> f
&&
(
(
g
)
||
h
)
;
i
我正在尝试为 C++ 中的程序实现自定义标记器。
示例代码
std::vector<std::string> Parser::tokenizeInput(std::string s) {
std::vector<std::string> returnTokens;
//tokenize correctly using this regex
std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");
std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
std::regex_iterator<std::string::iterator> rend;
while (rit!=rend) {
std::string tokenStr = rit->str();
if(tokenStr.size() > 0 && tokenStr != " "){
//assure the token is not blank
//and push the token
boost::algorithm::trim(tokenStr);
returnTokens.push_back(tokenStr);
}
++rit;
}
return returnTokens;
}
示例驱动程序代码
//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
std::cout << testVec[i];
if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;
产生的输出
input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]
input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]
input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]
我想要的输出是什么
input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]
input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]
input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]
【问题讨论】:
-
您使用哪种编程语言?我们可以尝试编写一个方法来做到这一点。使用 Java String
split()会很容易。 -
我正在使用 C++,我会更新我的问题以包含它。
-
你试过我的解决方案了吗?
-
也许this 可以吗?