如何避免反斜线在C / C ++编写正前pression ++时 [英] How to avoid backslash escape when writing regular expression in C/C++

查看:138
本文介绍了如何避免反斜线在C / C ++编写正前pression ++时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关定期EX pression \\ w + \\ D,在很多的脚本语言如Perl / Python的,可以从字面上写的。但在C / C ++,我必须把它写成:

For regular expression \w+\d, in many script language such as perl/python it can be written literally. But in C/C++, I must write it as:

const char *re_str = "\\w+\\d";

这是丑陋的眼睛。

which is ugly to eye.

有没有方法来避免呢?宏也是可接受的。

Is there any method to avoid it? MACRO are also acceptable.

推荐答案

当我阅读[C:参考手册]第3章:pre pressors。一个想法出现了:

When I reading [C: A reference manual] Chapter 3: Prepressors. An idea emerges:

 #define STR(a) #a
 #define R(var, re)  static char var##_[] = STR(re);\
 const char * var = ( var##_[ sizeof(var##_) - 2] = '\0',  (var##_ + 1) );

 R(re, "\w\d");
 printf("Hello, world[%s]\n",  re);

这是在C和C ++便携,只使用标准的preprocessing功能。诀窍是使用宏来扩大\\ liternal字符串中,然后取出领先和尾矿双引号的字符串。

It's portable in both C and C++, only uses standard preprocessing features. The trick is to use macro to expand \ inside liternal string and then remove the leading and tailing double quote strings.

现在我认为这是到的C ++ 0x真正引入新的文本字符串语法R...的最佳途径。而对于C,我认为这将是很长一段时间的最佳方式。

Now I think it's the best way until C++0x really introduce the new literal string syntax R"...". And for C I think it'll be the best way for a long time.

副作用是,我们不能在C.在全球范围内定义这样的变量,因为有去除拖尾双引​​号的声明。在C ++中它的确定。

The side effect is that we cannot defined such a variable in the global scope in C. Because there's a statement to remove the tailing double-quote character. In C++ it's OK.

这篇关于如何避免反斜线在C / C ++编写正前pression ++时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆