为了账号安全,请及时绑定邮箱和手机立即绑定

正则表达式匹配括号外的文本

正则表达式匹配括号外的文本

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 关注
    • 521 浏览

    添加回答

    举报

    0/150
    提交
    取消
    微信客服

    购课补贴
    联系客服咨询优惠详情

    帮助反馈 APP下载

    慕课网APP
    您的移动学习伙伴

    公众号

    扫描二维码
    关注慕课网微信公众号