c ++正则表达式:替换\ d \ s(用\ d *(

时间:2015-05-01 20:11:09

标签: c++ regex

在字符串ss中,如何将"3 ("替换为"3*("? (它通常适用于任何数字。)

std::string result;
std::string ss;
static const std::regex nn1 ("\\)(\\d)");
static const std::regex nn2 ("(\\d)(\\s\\()");

ss = "5 + 3 (2 + 1)";
std::regex_replace (std::back_inserter(result), ss.begin(), ss.end(), nn2, "\d*($2");
std::cout << result << "\n";

编译器错误第7行 - '\d'是一个无法识别的转义序列。 (我在那里试过'\\d'。)

MS Visual Studio 2013

(不是提出的问题的愚蠢,因为这涉及更改字符而不是插入一个字符,这处理了您不能在替换字符串中使用正则表达式的限制,并且必须解决这个问题,首先使用$ 1解决所选答案。)

2 个答案:

答案 0 :(得分:1)

作为此类字符串的更通用方法(但使用一个括号)您可以使用以下正则表达式:

: Exception

并替换为:

(\d)\s?\(

$1\*\( 将匹配正则表达式中的第一个组,即括号前的数字。

编辑:在c ++中你可以这样做:

$1

答案 1 :(得分:0)

try {
    ResultString = TRegEx::Replace(SubjectString, "\"(\\d+) \\(\"", "\"$1*(\"", TRegExOptions() << roSingleLine << roMultiLine);
} catch (ERegularExpressionError *ex) {
    // Syntax error in the regular expression
}

正则表达式解释:

"(\d+) \("

Options:  Exact spacing; Dot matches line breaks; ^$ match at line breaks; Numbered capture

Match the character “"” literally «"»
Match the regex below and capture its match into backreference number 1 «(\d+)»
   Match a single character that is a “digit” «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “ ” literally « »
Match the character “(” literally «\(»
Match the character “"” literally «"»

"$1*("

Insert the character “"” literally «"»
Insert the text that was last matched by capturing group number 1 «$1»
Insert the character string “*("” literally «*("»