簡體   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