繁体   English   中英

在另一个字符串python正则表达式多行之后找到第一个匹配项

[英]Find first match following another string, python regex multiline

我知道已经问过许多这样的问题,但是让正则表达式声明来解决我的特定问题有点麻烦。

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

请注意,我正在使用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;)

我建议改用此正则表达式。

(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.

为了更好地理解,请在此处进行实验。 希望这就是您想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM