匹配短语的正则表达式,除非它已经加前缀

标签 regex sed

我正在清理一个大型 C++ 代码库,其中我需要将“vector”类型的所有变量更改为“std::vector”。跳过代码中的#include 和注释。最重要的是,如果表达式已经写成“std::vector”,不要将它转换为“std::std::vector”

那是:

#include <vector>
vector<Foo> foolist;
typedef vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
    // this vector is for iteration
    for (vector <Foo>::iterator itor = foo.begin...)

转换为
#include <vector>
std::vector<Foo> foolist;
typedef std::vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
    // this vector is for iteration
    for (std::vector<Foo>::iterator itor = foo.begin...)

到目前为止,我已将其范围缩小到两个 sed 命令
sed -r 's/vector\s{0,1}</std::vector</g' < codefile > tmpfile
sed 's/std::std/std/' < tmpfile > codefile

第一个 sed 匹配 "vector< 和 "vector <"并转换为 "std::vector<"。

第二个 sed 修复了将“std::vector<”转换为“std::std::vector<”的副作用。

如何合并上面两个不同的正则表达式,以便我可以使用单个 sed 命令来正确修复代码。

我试过在网上阅读关于前瞻和后视的内容,但我的眼睛开始烧焦了。

最佳答案

您可以使第一个正则表达式也匹配可能的 std::通过使用

sed -r 's/[std:]*vector\s{0,1}</std::vector</' < codefile > tmpfile

顺便说一句:您可以通过添加 -i 来进行适当的更改并将文件作为命令行参数传递:
sed -i -r 's/[std:]*vector\s{0,1}</std::vector</' codefile

关于匹配短语的正则表达式,除非它已经加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11464121/

相关文章:

bash - 如何在不排序的情况下删除两个文件之间的公共(public)行?

linux - sed 匹配后替换

regex - 用sed替换超过150000个字符

c - scanf 格式化字符串

javascript - 当字符串包含括号时如何配置 RegExp

java - 匹配器需要正则表达式

linux - 从文本文件第一行的开头删除匹配的模式

c# - 正则表达式仅从字符串中获取数字

regex - 如何在 Bash 中拆分 URL 参数

regex - 使用 sed 删除子字符串