亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正則表達式匹配括號外的文本

正則表達式匹配括號外的文本

C#
MMTTMM 2022-01-09 17:38:19
我目前正在使用這個正則表達式,但可以弄清楚如何讓文本組組合它的結果。String: Text 1^%+{TAB}({CMD 1}{CMD 2})Text 2.^(abc)Regex: (?<special>[\^+%]*?[\(][^)]*[\)])|(?<special>[\^+%]*?[\{][^}]*[\}])|(?<text>.)Result:    text: T    text: e    text: x    text: t    text:      text: 1    special: ^%+{TAB}    special: ({CMD 1}{CMD 2})    text: T    text: e    text: x    text: t    text:      text: 2    special: ^(abc)Wanted:    text: Text 1    special: ^%+{TAB}    special: ({CMD 1}{CMD 2})    text: Text 2    special: ^(abc)最終,我希望“文本 1”和“文本 2”成為文本組中的兩個組。在我的一生中添加 .*?(..) 時,似乎無法讓文本組不干擾特殊組。
查看完整描述

2 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

您可以使用

(?<special>[+^%]*(?:\([^)]*\)|{[^}]*}))|(?<text>[\w\s]+)

請參閱正則表達式演示。

細節

  • (?<special>[+^%]*(?:\([^)]*\)|{[^}]*})) - 組“特殊”捕獲:

    • \([^)]*\)- a (,然后是 0+ 字符),然后是 a)

    • | - 或者

    • {[^}]*}- a {,然后是 0+ 字符},然后是 a}

    • [+^%]*- 零個或多個+^%字符

    • (?:-匹配以下兩種選擇之一的非捕獲組

    • ) - 非捕獲組的結束。

    • | - 或者

    • (?<text>[\w\s]+) - 組“文本”:一個或多個單詞或空格字符。


    查看完整回答
    反對 回復 2022-01-09
    ?
    慕運維8079593

    TA貢獻1876條經驗 獲得超5個贊

    嘗試以下:


                string input = "Text 1^%+{TAB}({CMD 1}{CMD 2})Text 2.^(abc)";

                string pattern = @"^(?'text1'[^\^]+)(?'special1'[^\(]+)(?'special2'[^\)]+\))(?'text2'[^\^]+)(?'special3'.*)";


                Match match = Regex.Match(input, pattern);

                Console.WriteLine("Text : '{0}' Special : '{1}' Special : '{2}' Text : '{3}' Special : '{4}'",

                    match.Groups["text1"].Value,

                    match.Groups["special1"].Value,

                    match.Groups["special2"].Value,

                    match.Groups["text2"].Value,

                    match.Groups["special3"].Value

                        );

                Console.ReadLine();


    查看完整回答
    反對 回復 2022-01-09
    • 2 回答
    • 0 關注
    • 443 瀏覽

    添加回答

    舉報

    0/150
    提交
    取消
    微信客服

    購課補貼
    聯系客服咨詢優惠詳情

    幫助反饋 APP下載

    慕課網APP
    您的移動學習伙伴

    公眾號

    掃描二維碼
    關注慕課網微信公眾號