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

2024-09-27 21:26:30 发布

您现在位置: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;

}

在这个例子中,我想找到函数名“writecwp\u positionStatus”后面的第一个“old\u intval=starting\u int;”。将有更多的函数具有相同的实体,但名称不同。你知道吗

我的想法是成立一个抓捕小组来匹配:

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

我尝试了一系列不同的选择,例如,但似乎每次都有一点偏离:

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

Tags: to函数invarvaloldlongint
1条回答
网友
1楼 · 发布于 2024-09-27 21:26:30

我建议用这个正则表达式来代替。你知道吗

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

这里,方法是捕获从函数名到要由capture group 01重新放置的语句的所有内容,然后通过capture group 02匹配statement之后的所有内容

\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。我希望这就是你想要的。你知道吗

相关问题 更多 >

    热门问题