2017-07-04 69 views
2

我想安裝一個條件。我已經嘗試了很多,但沒有成功。有人會如此善良,會幫助我嗎?正則表達式搜索文本然後匹配元素

我的目標:如果SharedKeys爲true,則匹配元素(A B C D)。

SharedKeys = 「A」, 「B」, 「C」, 「d」

正則表達式:(?!\")[A-Z]*?(?=\")

匹配元素:ABCD

更新:(SharedKeys)?(?(1)|(?!\")[A-Z]*?(?=\"))

匹配元素:SharedKeys ABCD

鏈接:https://regex101.com/r/WFxZh4/1

我想我現在有我需要的東西,也許可以幫助別人。

SharedKeys = 「A」, 「B」, 「C」, 「d」

BLABLA = 「B」, 「B」, 「C」

結果:(SharedKeys|BlaBla)?(?(1)|(?!\")[A-Z]*?(?=\"))

匹配元素:對於C++ SharedKeys ABCD BLABLA BBC

結果:[A-Za-z]+|(?!\")[A-Z]*?(?=\")(標準::正則表達式)

+0

你是什麼意思** SharedKeys ** –

+0

有些時候更容易匹配'Sendkeys = ....'然後匹配最近匹配的字符串中的元素,分兩步@Lendoria – MohaMad

+0

謝謝你的回答,你能舉個小例子嗎? – Lendoria

回答

1

std::regex

std::string s1(R"(SharedKeys = "A","B","C","D")"); 
std::regex rx("(SharedKeys)?(?(1)|[A-Z](?=\\\"))"); 
std::match_results<std::string::const_iterator> mr; 

while(std::regex_search(s1, mr, rx)){ 
    std::cout << mr.str() << '\n'; 
    s1 = mr.suffix().str(); 
} 

輸出:

terminate called after throwing an instance of 'std::regex_error' 
what(): Invalid special open parenthesis. Aborted (core dumped) 

boost::regex

std::string s1(R"(SharedKeys = "A","B","C","D")"); 
boost::regex rx("(SharedKeys)?(?(1)|[A-Z](?=\\\"))"); 
boost::match_results<std::string::const_iterator> mr; 

while(boost::regex_search(s1, mr, rx)){ 
    std::cout << mr.str() << '\n'; 
    s1 = mr.suffix().str(); 
} 

輸出:

SharedKeys 
A 
B 
C 
D 

在這裏你可以看到區別這兩種風格之間:

boost_regex_table

source of the screenshot


注意。 std::regex是特別與gcc version 6.3.0 and lower versions

+0

感謝您的描述!我只使用std:regex,所以我寫了另一個algorythm。在未來,也許我添加Boost:正則表達式。謝謝! – Lendoria

+0

@Lendoria。不用謝。它更快,更豐富,更安全 –