2015-05-01 83 views
3

在字符串SS,我怎麼更換"3 (""3*(" (它需要在一般工作的任何數字)C++的正則表達式:?替換 d S(用 d *(

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解決。)

+0

我有一個大致的要求:當你獲得幫助,請還清與upvotes和接受的答案。 –

+0

[C++ regex \ _replace不做預期替換]的可能重複(http:// stackoverflow。com/questions/29991889/c-regex-replace-not-doing-intended-substitution) – AndyG

+0

我鏈接的dup是另一個基本相同的問題,Mike。 – AndyG

回答

1

對於這樣的字符串(但有一個括號),您可以使用下面的正則表達式更通用方式:

(\d)\s?\(

,代之以:

$1\*\(

$1將在您的正則表達式中匹配第一組是數字 在括號之前。

編輯:在C++中,你可以這樣做:因爲您使用的是C++字符串,並不存在內部的轉義序列\d發生

std::regex_replace (std::back_inserter(result), ss.begin(), ss.end(), nn2, "$1\*\("); 
+0

謝謝。我沒有意識到你不能在C++中用/ d替代,你必須解決這個問題。此更改的工作原理如下: std :: regex_replace(std :: back_inserter(result),ss.begin(),ss.end(),nn2,「$ 1 \\ * \\(」); –

+0

此外,我沒有 –

+0

@MikeSmith Your're welcome!我添加了你的建議!;) – Kasramvd

1

編譯器錯誤。更糟糕的是,你正嘗試在替換字符串中使用正則表達式模式,這不是你想要的。你想在那裏使用一些文字字符串,反向引用的類型爲$1$ + digit referring to the capturing group in a regex pattern)。

使用此代碼:

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, "$1*("); 
std::cout << result << "\n"; 

輸出:

enter image description here

nn2變量將持有的正則表達式(\d+)\s*\(,將捕獲

  • (\d+) - 數字,1或更多,但儘可能多,並且將放置在第1組
  • \s*\( - 0或多個空格,和一個文字開口輪托架

更換時,我們將參照第一組作爲$1。不需要轉義*(

+0

不,在替換字符串中使用正則表達式模式正是我想要做的,但看起來你不能做用C++的那個功能,所以你必須解決這個限制。謝謝你的幫助。然而,你的回答確實提供了幫助,但我選擇的答案更接近我所問的。 –

+0

如果你在'3'和'('之間有一個以上的空格,你選擇的答案將會失敗。無論如何,你可以積極地表示感謝:)只是另一個「怨恨」:Kasra在他的'\ 1'中原來的答案,而不是「$ 1」,他看到我的回答後,他相應地更新。 –

+0

好的。你改變了很多東西。我不需要d +,也不需要s *,因爲這個問題規範總是隻有一個空間。無論如何,我現在有足夠的票數可以贊成,所以我這樣做了,因爲你的答案確實包含了解決方案。謝謝。 –

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 «*("» 
相關問題