如何逃脱的升压使用正则表达式的字符串 [英] How to escape a string for use in Boost Regex
问题描述
我刚开始我的周围经常EX pressions头,我使用正则表达式加速库。
我有一个需要使用正则表达式包含特定的URL,它闷死了,因为明明有在URL中的字符保留给正则表达式,需要进行转义。
是否有Boost库的函数或方法逃避这种用法的字符串?我知道有其他大多数正则表达式实现这样的方法,但我看不出之一的推动作用。
另外,有将需要转义所有字符的列表?
。 ^ $ | ()[] {} * +? \\
讽刺的是,你可以使用正则表达式来逃避你的网址,以便它可以被插入到一个正则表达式。
常量的boost ::正则表达式ESC([^ $ |()\\\\ [\\\\] {} * + \\\\\\\\?]);
常量标准::字符串代表(\\\\\\\\&安培;);
性病::字符串结果= regex_replace(url_to_escape,ESC,代表,
提高::了match_default |提高:: format_sed);
(旗 的boost :: format_sed
指定要使用的替换字符串格式的sed在sed,逃避&放大器;
将输出无论由整个前pression匹配)
或者,如果你不舒服的sed的替换字符串格式,只需更改标志的boost :: format_perl
,你可以使用熟悉的 $&安培;
来指任何由整个前pression匹配
常量标准::字符串代表(\\\\\\\\ $&安培;);
性病::字符串结果= regex_replace(url_to_escape,ESC,代表,
提高::了match_default |提高:: format_perl);
I'm just getting my head around regular expressions, and I'm using the Boost Regex library.
I have a need to use a regex that includes a specific URL, and it chokes because obviously there are characters in the URL that are reserved for regex and need to be escaped.
Is there any function or method in the Boost library to escape a string for this kind of usage? I know there are such methods in most other regex implementations, but I don't see one in Boost.
Alternatively, is there a list of all characters that would need to be escaped?
. ^ $ | ( ) [ ] { } * + ? \
Ironically, you could use a regex to escape your URL so that it can be inserted into a regex.
const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]");
const std::string rep("\\\\&");
std::string result = regex_replace(url_to_escape, esc, rep,
boost::match_default | boost::format_sed);
(The flag boost::format_sed
specifies to use the replacement string format of sed. In sed, an escape &
will output whatever matched by the whole expression)
Or if you are not comfortable with sed's replacement string format, just change the flag to boost::format_perl
, and you can use the familiar $&
to refer to whatever matched by the whole expression.
const std::string rep("\\\\$&");
std::string result = regex_replace(url_to_escape, esc, rep,
boost::match_default | boost::format_perl);
这篇关于如何逃脱的升压使用正则表达式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!