在另一个字符串python regex multiline之后找到第一个匹配项

时间:2017-07-12 14:53:12

标签: python regex

我知道这些问题已经有很多种问题,但是我在制作正则表达式语句以解决我的具体问题时遇到了一些麻烦。

我有大量具有不同名称但功能完全相同的函数,我需要找到特定函数名后的第一个匹配项。

请注意,我正在使用python搜索C文件。

 writecwp_positionStatus(int      action,
        u_char   *var_val,
        u_char   var_val_type,
        size_t   var_val_len,
        u_char   *statP,
        oid      *name,
        size_t   name_len) {

static long     intval;
static long     old_intval;

switch ( action ) {
    case RESERVE1:
      if (var_val_type != ASN_INTEGER) {
          fprintf(stderr, "write to mib not ASN_INTEGER\n");
          return SNMP_ERR_WRONGTYPE;
      }
      if (var_val_len > sizeof(long)) {
          fprintf(stderr,"write to mib: bad length\n");
          return SNMP_ERR_WRONGLENGTH;
      }
    intval = *((long *) var_val);
      break;

    case RESERVE2:
      break;

    case FREE:
         /* Release any resources that have been allocated */
      break;

    case ACTION:
         /*
          * The variable has been stored in 'value' for you to use,
          * and you have just been asked to do something with it.
          * Note that anything done here must be reversable in the UNDO case
          */
        old_intval = starting_int;
        starting_int = intval;
      break;

    case UNDO:
         /* Back out any changes made in the ACTION case */
         starting_int = old_intval;
      break;

    case COMMIT:
         /*
          * Things are working well, so it's now safe to make the change
          * permanently.  Make sure that anything done here can't fail!
          */
      break;
} return SNMP_ERR_NOERROR;

}

在这个例子中,我想找到第一个“old_intval = starting_int;”在函数名称“writecwp_positionStatus”之后。将会有更多具有相同主体但名称不同的功能。

我的想法是设置一个匹配的捕获组:

(function name)(everything in between including newlines)(line to replace)

我尝试了许多不同的选项,例如,但每次似乎只有一点点:

(writecwp_positionStatus\(.*\s)((.*\s)*?)(\s*old_intval = starting_int;)

1 个答案:

答案 0 :(得分:2)

我会建议这个正则表达式。

(writecwp_positionStatus[\s\S]*?)old_intval = starting_int;([\s\S]*)

这里,方法是捕获从函数名称到捕获组01 要修复的语句的所有内容,然后通过捕获组02

\s -> whitespace character (a space, a tab, a line break, or a form feed).
\S -> non-white space character.
*? -> ? after quantifiers makes them lazy/non-greedy.

现在要替换该语句,我们可以使用另一个正则表达式:

\1 >>>I am the replacement<<< \2

在这里,

\1 -> Everything before the statement.
\2 -> Everything after the statement.

为了更好地理解,请进行实验here。我希望这就是你想要的。