【问题标题】:Extracting sub string with regexp使用正则表达式提取子字符串
【发布时间】:2013-12-08 17:17:24
【问题描述】:

我的源代码文件中有以下类型的文本:

html += T.m('current value of the quality level of the security service (as established from the diagnostic phase).');
or
{header: T.m("Service to Improve"), dataIndex : 'searvicesToImprove', hideable: false},
or
Ext.getCmp('MAX_ACTION_PLANS_PAGE').setText(T.m('od') + ' ' + MAX_ACTION_PLANS_PAGE);

我想提取括号内的子字符串,即。从 T.m(X) 我想得到不带引号或带引号的 X,然后我会修剪它们。

所以换句话说,我想要这样的东西

regex( "T.m('X')" | "T.m("X")" );
and then say:
listOfMatches.add(X);

我知道这通常是用 regexp 完成的,但我对 regexp 不是很好,没有使用太多,仅用于基本示例。 非常感谢任何帮助。

【问题讨论】:

    标签: c# regex string substring extraction


    【解决方案1】:
    try {
        Regex regexObj = new Regex(@"T\.m\([""|'](.+?)[""|']\)");
        Match matchResults = regexObj.Match(subjectString);
        while (matchResults.Success) {
            var neededvalue = matchResults.Groups[1].Value;
        } 
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }
    

    【讨论】:

    • 空试捕获。啊!
    • @AppDeveloper 添加评论不代表不为空。
    • @SriramSakthivel - 啊,我读错了那个声明!对不起!
    • 感谢一百万,与其他人不同,您是唯一不破坏格式“T.m(stuff)”的人。这就是为什么我将您的答案标记为正确的原因。
    【解决方案2】:
    var regex = new Regex(@"T\.m\((?<MyGroup>.*)\)");
    var match =regex.Match(subject);
    if(match.Success)
    {
        var found =  match.Groups["MyGroup"].Value;
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用正则表达式并希望所有部分分开,这可能会起作用

       #  @"(?s)T\.m\(((['""])((?:(?!\2).)*)\2)\)"
      
       (?s)                          # dot all modifier
       T \. m                        # 'T.m'
       \(                            # Open parenth
       (                             # (1 start), Quoted part
            ( ['"] )                      # (2), Open Quote
            (                             # (3 start), Body of quoted part
                 (?:                           # grouping
                      (?! \2 )                      # lookahead, not a quote
                      .                             # any char
                 )*                            # end grouping, do 0 or more times
            )                             # (3 end)
            \2                            # Close quote (group (2) backreference)
       )                             # (1 end), Quoted part
       \)                            # Close parenth
      

      从群组中获取你需要的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 2023-04-06
        • 2018-08-28
        相关资源
        最近更新 更多