我需要在R中从SQL语句的字符串中删除以
使用前瞻和后顾已经取得了一些关于那些在行首开始的注释/标记的进展:
但显然,这不能处理字符串中其他地方的注释:
--
开头的注释。我尝试使用正则表达式和gsub
(但我也愿意接受其他建议)来完成这个任务。复杂的是,这些字符串可能包含以--->>>
开头并以<<<---
结尾的特殊标记,我需要保留它们以进行进一步处理。使用前瞻和后顾已经取得了一些关于那些在行首开始的注释/标记的进展:
> re <- "^(?!=<<<-){1}--(?!->>>){1}.*$"
>
> gsub(re, "", "-- test", perl=TRUE) # should be ""
[1] ""
> gsub(re, "", "--->>> test", perl=TRUE) # should be "--->>> test"
[1] "--->>> test"
> gsub(re, "", "<<<--- test", perl=TRUE) # should be "<<<--- test"
[1] "<<<--- test"
> gsub(re, "", "--->>>->>> test", perl=TRUE) # should be --->>>->>> test
[1] "--->>>->>> test"
> gsub(re, "", "---->>> test", perl=TRUE) # should be ""
[1] ""
> gsub(re, "", "test --->>> test", perl=TRUE) # should be "test --->>> test"
[1] "test --->>> test"
> gsub(re, "", "test --->>> test <<<---", perl=TRUE) # should be "test --->>> test <<<---"
[1] "test --->>> test <<<---"
但显然,这不能处理字符串中其他地方的注释:
> gsub(re, "", "test1 -- test", perl=TRUE) # should be "test1"
[1] "test1 -- test" # WRONG
在正则表达式开头删除^
会破坏大多数测试用例:
> re <- "(?!=<<<-){1}--(?!->>>){1}.*$"
> gsub(re, "", "-- test", perl=TRUE) # should be ""
[1] ""
> gsub(re, "", "test1 -- test", perl=TRUE) # should be "test1"
[1] "test1 "
> gsub(re, "", "--->>> test", perl=TRUE) # should be "--->>> test"
[1] "-" # WRONG
> gsub(re, "", "<<<--- test", perl=TRUE) # should be "<<<--- test"
[1] "<<<" # WRONG
> gsub(re, "", "--->>>->>> test", perl=TRUE) # should be --->>>->>> test
[1] "-" # WRONG
> gsub(re, "", "---->>> test", perl=TRUE) # should be ""
[1] ""
> gsub(re, "", "test --->>> test", perl=TRUE) # should be "test --->>> test"
[1] "test -" # WRONG
> gsub(re, "", "test --->>> test <<<---", perl=TRUE) # should be "test --->>> test <<<---"
[1] "test -" # WRONG
有人有关于如何实现这个的建议吗?我接受任何建议,但是必须使用R,并且必须保留特殊标签--->>>
和<<<---
。
编辑
如评论中所述,这也是一个测试用例:
> gsub(re, "", "-->>> test", perl=TRUE) # should be ""
"--->>>->>> test"
没有被移除,而"---->>> test"
应该被移除? - Avinash Raj"(?<!-)--->>>.*?<<<---(?!-)(*SKIP)(*F)|(?<!-)--(?!-).*"
。标签总是在一行上吗?还是可能会有换行符? - Wiktor Stribiżew(?:^|\w)\s*--\s*\b.*|\s*-{4,}.*
- Avinash Raj(?:(?<!-)--->>>|<<<---(?!-))(*SKIP)(*FAIL)|--.*
尝试一下。然而,此时我怀疑它对你帮助不大。 - Wiktor Stribiżew