简体   繁体   English

如何使用Boost正则表达式检测字符串中的ESC

[英]How to detect ESC in string using Boost regex

I need to determine if a file is PCL encoded. 我需要确定文件是否是PCL编码的。 So I am looking at the first line to see if it begins with an ESC character. 所以我正在查看第一行,看它是否以ESC字符开头。 If you know a better way feel free to suggest. 如果您知道更好的方式随意建议。 Here is my code: 这是我的代码:

bool pclFlag = false;
if (containStr(jobLine, "^\\e")) {
   pclFlag=true;
}

bool containStr(const string& s, const string& re)
{
   static const boost::regex e(re);
   return regex_match(s, e);
}

pclFlag does not get set to true. pclFlag未设置为true。

You've declared boost::regex e to be static, which means it will only get initialized the very first time your function is called. 你已经声明boost::regex e是静态的,这意味着它只会在你的函数第一次被调用时被初始化。 If your search here is not the first call, it will be searching for whatever string was passed in the first call. 如果您的搜索不是第一次调用,它将搜索第一次调用中传递的任何字符串。

regex_match must match the entire string. regex_match必须匹配整个字符串。 Try adding ".*" (dot star) to the end of your regex. 尝试在正则表达式的末尾添加“。*”(点星)。

Important 重要
Note that the result is true only if the expression matches the whole of the input sequence. 请注意,仅当表达式与整个输入序列匹配时,结果才为真。 If you want to search for an expression somewhere within the sequence then use regex_search. 如果要在序列中的某处搜索表达式,请使用regex_search。 If you want to match a prefix of the character string then use regex_search with the flag match_continuous set. 如果要匹配字符串的前缀,请使用regex_search并设置标志match_continuous。
http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/ref/regex_match.html http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/ref/regex_match.html

@JoachimPileborg is right... if (jobline[0] == 0x1B) {} is much easier. @JoachimPileborg是对的... if (jobline[0] == 0x1B) {}更容易。

Boost.Regex seems like overkill if all you want to do is see if a string starts with a certain character. 如果你想要做的就是看一个字符串是否以某个字符开头,Boost.Regex似乎有些过分。

bool pclFlag = jobLine.length() > 0 && jobLine[0] == '\033';

You could also use Boost string algorithms: 您还可以使用Boost字符串算法:

#include <boost/algorithm/string.hpp>

bool pclFlag = jobLine.starts_with("\033");

If you're looking to see if a string contains an escape anywhere in the string: 如果您正在查看字符串中的字符串是否包含转义:

bool pclFlag = jobLine.find('\033') != npos;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM