【问题标题】:Regex-ed value to String正则表达式值到字符串
【发布时间】:2016-12-08 17:38:06
【问题描述】:

我创建了这个正则表达式并使用该值打印成一个字符串。

 std::string s (filename);
  std::smatch m;
  std::regex e ("\/(?:.(?!\/))+$");   

  while (std::regex_search (s,m,e)) {
    for (auto p:m) std::cout << p << " ";

    s = m.suffix().str();   
  }
    std::string currFileName = s;

    std::string Original = filename;
    std::string newFile = Original + currFileName;
    std::cout << newFile;

问题是它没有显示在终端中。

印值

/simple-loops.cc /home/fypj/build/simple-loops.cc

预期值

/home/fypj/build/simple-loops.cc/simple-loops.cc

你可能会问文件名是什么

llvm::StringRef filename;
SourceLocation ST = f->getSourceRange().getBegin();
filename = Rewrite.getSourceMgr().getFilename(ST);

【问题讨论】:

  • 是的,那么文件名字符串是什么样的呢?打印出来的值和传入的一样吗?
  • @wiktorstribizew /home/fypj/build/simple-loops.cc/
  • 是不是要截断最后一个/处的字符串?
  • @wiktorstribizew 是的

标签: c++ regex clang


【解决方案1】:

注意:也许,最好的方法是使用Getting a directory name from a filename 帖子中描述的路径操作方法。

回答你的问题...

您正在尝试匹配路径的最后一部分并将其附加到末尾。您使用的正则表达式与您的字符串不匹配,因为您想匹配最后一个 / 之后的 一个 或多个字符,而不是 / - 但您的输入以 / 结尾。 "\/(?:.(?!\/))+$" 还包含 \/ 错误的转义序列,您不应该转义 / 符号。请注意,当您只需要“否定”一个符号时,这种缓和的贪婪令牌之类的构造效率不高 - 您需要 negated character class

因此,如果您想使用正则表达式,请使用占/s 的模式并将其与regex_replace 一起使用:

#include <iostream>
#include <regex>
using namespace std;

int main() {
    std::regex reg("/?([^/]+)/?$");
    std::string s("/home/fypj/build/simple-loops.cc/");
    std::cout << std::regex_replace(s, reg, "/$1/$1/") << std::endl;
    return 0;
}

C++ demo

模式详情

  • /? - 可选/
  • ([^/]+) - 第 1 组(可以在替换模式中使用 $1 引用)捕获除 / 之外的一个或多个符号([^...] 是一个否定字符类
  • $ - 字符串结束

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2013-12-15
相关资源
最近更新 更多