使用C ++ 11的正则表达式通过反斜杠转义正斜杠

时间:2015-01-23 23:57:56

标签: c++ c++11

我需要通过反斜杠匹配转义正斜杠的任何字符串。

一些例子(在c ++字符串中,你需要两次以上的反斜杠然后在exmaples中):

sdfsdfkjl/sdf  // does not match
sdfsdfkj\/sdf  // does match
sdfsdfk\\/sdf  // does not match
sdfsdf\\\/sdf  // does match
sdfsdfk\\/sd\\\/f  // does not match
sdfsdf\\\/sdf\\\/f  // does match
// and so on

我想应该有这样的东西

std::regex const regEx(
  "((?:(?:(?!\\\\)\\\\/)|(?:(?:\\\\\\\\)+\\\\/)|(?:[^/]))*)");

但由于某些原因它不起作用。我的猜测是它与前瞻操作有关。

2 个答案:

答案 0 :(得分:0)

您是否使用原始字符串文字初始化正则表达式对象?

原始字符串文字具有以下格式......

R"()"

所以正则表达式初始化看起来像这样......

regex pat{R"()"};

你也可以在"之间放置你想要的任何分隔符。和(或)能够匹配任何序列。

如果你尝试使用两种类型的斜杠作为分隔符的格式,你会得到匹配吗?说,像这样......

regex pat{R"\\/()\\/"};

答案 1 :(得分:0)

#include <iostream>
#include <regex>

int main()
{
    auto test_patterns = {
      R"(sdfsdfkjl/sdf)",
      R"(sdfsdfkj\/sdf)",
      R"(sdfsdfk\\/sdf)",
      R"(sdfsdf\\\/sdf)",
      R"(sdfsdfk\\/sd\\\/f)",
      R"(sdfsdf\\\/sdf\\\/f)"
    };

    std::cout << "With regex_search\n";
    std::regex r1(R".(^[^\\/]*(\\\\)*\\/).");    
    for (const auto& pattern: test_patterns) {
        std::cout << pattern << " : " <<
            (std::regex_search(pattern, r1) ? "match" : "no match") << std::endl;
    }

    std::cout << "\nWith regex_match\n";
    std::regex r2(R".(^[^\\/]*(\\\\)*\\/.*).");    
    for (const auto& pattern: test_patterns) {
        std::cout << pattern << " : " <<
            (std::regex_match(pattern, r2) ? "match" : "no match") << std::endl;
    }
}

输出:

With regex_search
sdfsdfkjl/sdf : no match
sdfsdfkj\/sdf : match
sdfsdfk\\/sdf : no match
sdfsdf\\\/sdf : match
sdfsdfk\\/sd\\\/f : no match
sdfsdf\\\/sdf\\\/f : match

With regex_match
sdfsdfkjl/sdf : no match
sdfsdfkj\/sdf : match
sdfsdfk\\/sdf : no match
sdfsdf\\\/sdf : match
sdfsdfk\\/sd\\\/f : no match
sdfsdf\\\/sdf\\\/f : match

Live example