作者cutekid (可爱小孩子)
看板C_and_CPP
标题Re: [问题] regex_replace取代非comment内的内容
时间Mon Oct 8 18:21:26 2018
以下处理 /* */ 这种的注解
#include <iostream>
#include <regex>
using namespace std;
int main() {
string text = "\/*comment 1*\/text1\n\/*comment 2*\/text2\n";
string pattern = "([\\s\\S]*?)((?:\/\\*[\\s\\S]+?\\*\/)|$)";
regex re(pattern);
cout << "pattern: " << pattern << endl;
cout << regex_replace(text,re,"$2");
return 0;
}
程式:
https://ideone.com/7eCkXG
参考:
http://www.cplusplus.com/reference/regex/regex_replace/
※ 引述《boy770329 (A-So)》之铭言:
: 问个regular expreesion的问题 因为试了很久还是找不到解
: 现在想用regex_replace去取代SQL query内的某个字串,条件是那个字串不在注解内
: 因为SQL的注解写法有一行的--或#
: 多行的/* ... */
: 然後C++的regex只支援lookahead 处理一行注解还可以,但是多行的就会有问题
: 目前写的regex 长这样 : ^(?:(?!\-\-)(?!\#).)*取代的字串regex
: 大致上就是遇到--或是#就assert不处理,这样可以有效跳过单行注解
: 用类似的逻辑想处理多行注解时就会遇到问题
: ^(?:(?!\-\-)(?!\#)(?!\/\*).)*取代的字串regex
: 因为query可能会长得像SELECT * /*注解*/ from table where...
: 会导致一遇到/*後面的东西也都不继续处理
: 试了半天还是想不到除了先把/*...*/从input query中去掉的解
: 不知道有没有版友有类似的经验可以用C++支援的regex语法处理跳过这种情况做replace
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.221.80.36
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1538994090.A.1CE.html
1F:推 art1: 原来是没把 \ 逸出的关系 10/08 22:42
2F:→ art1: c++ 没支援 raw string 真可惜 10/08 22:43
3F:推 thefattiger: committee:我们听到了 10/08 22:46
4F:→ thefattiger: 估狗了一下, C++有raw string耶,类似Python的写法 10/08 22:52
5F:推 art1: 原来有,那用 raw string 还是比较方便,逸出好麻烦的 10/08 23:23
6F:推 LPH66: raw string 是 C++11 才有的新语法喔, 不过比 python 方便 10/09 17:19
7F:→ LPH66: C++11 的 raw string 有多一对括号, 括号外还能塞东西 10/09 17:20
8F:→ LPH66: 这些都是用来避免已经写了 raw string 还要跳脱东西 10/09 17:20
9F:推 art1: 不懂撷取 group 2 的目的是什麽,如果是我的话会写成这样 10/10 22:44
10F:→ art1: ([\\s\\S]*?)(?:\/\\*[\\s\\S]+?\\*\/|$) 10/10 22:44
11F:→ cutekid: 非注解替换,保留注解 10/11 00:08