如何将字符串转换为正则表达式

编程入门 行业动态 更新时间:2024-10-27 02:22:35
本文介绍了如何将字符串转换为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在正则表达式中使用任意 std :: wstring 的最佳方法是什么?例如,将您欠我$ 转换为您欠我\ $ ?

我的场景:我想使用 std :: tr1 :: wregex 来搜索整个单词。所以我想做一些像:

std :: wstring RegexEscape(const std :: wstring& inp) { return ??? } bool ContainsWholeWord(const std :: wstring& phrase,const std :: wstring& word) { std :: tr1 :: wregex regex std :: wstring(L\\b)+ RegexEscape(word)+ L\\b); return std :: tr1 :: regex_match(phrase,regex); }

解决方案

我不知道它是最聪明的或最高效的,但我使用类似如下:

命名空间{ bool isMeta(char ch) { static bool const meta [UCHAR_MAX] = { // ... } return meta [static_cast< unsigned char>(ch)]; } std :: string sanitizeForRegEx(std :: string const& original) { std :: string result; for(std :: string :: const_iterator iter = original.begin(); iter!= original.end(); ++ iter){ if (* iter)){ result + ='\\'; result + = * iter; } return result; }

对于 wchar_t 我将修改 isMeta 以返回类似于:

; = 0&& ch < 128&&元[ch]

meta 的初始化有点一个钻孔,确切的值取决于所使用的正则表达式(如果使用 boost :: regex ,甚至使用选项)。

What's the best way to escape an arbitrary std::wstring for use inside a regular expression? For example, convert you owe me $ to you owe me \$?

My scenario: I want to use a std::tr1::wregex to search for a whole word. So I want to do something like:

std::wstring RegexEscape(const std::wstring& inp) { return ????? } bool ContainsWholeWord(const std::wstring& phrase, const std::wstring& word) { std::tr1::wregex regex(std::wstring(L"\\b") + RegexEscape(word) + L"\\b"); return std::tr1::regex_match(phrase, regex); }

解决方案

I don't know that it's the cleverest or the most efficient, but I use something like the following:

namespace { bool isMeta( char ch ) { static bool const meta[UCHAR_MAX] = { // ... }; return meta[static_cast<unsigned char>( ch )]; } std::string sanitizeForRegEx( std::string const& original ) { std::string result; for ( std::string::const_iterator iter = original.begin(); iter != original.end(); ++ iter ) { if ( isMeta( *iter ) ) { result += '\\'; result += *iter; } return result; }

For wchar_t, I'd modify isMeta to return something like:

return ch >= 0 && ch < 128 && meta[ ch ];

The initialization of meta is a bit of a bore, and the exact values depend on the regular expressions used (or even the options if boost::regex is used).

更多推荐

如何将字符串转换为正则表达式

本文发布于:2023-11-05 09:04:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   如何将   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!