我正在尝试从以下sample.log中提取一些单词(如预期的输出所示)。我在提取最后的预期输出(即xuvs)时遇到困难。该代码可以提取除最后一个输出之外的所有输出。我正在尝试找到如何对正则表达式进行编码,以暗指“查找文本后跟空格或(”。任何其他方法的指针都将受到赞赏。

sample.log

  for (i=0; i< models; i = i+1) begin:modelgen

 model_ip model_inst
     (
      .model_powerdown(model_powerdown),
      .mcg(model_powerdown),
      .lambda(_lambda[i])
      );
  assign fnl_verifier_lock = (tx_ready & rx_ready) ? &verifier_lock :1'b0;

native_my_ip native_my_inst
 (
  .tx_analogreset(tx_analogreset),
 //.unused_tx_parallel_data({1536{1'b0}})

  );

// END Section I

resync
 #(
   .INIT_VALUE (1)
   ) inst_reset_sync
   (
.clk    (tx_coreclkin),
.reset  (!tx_ready), // tx_digitalreset from reset
.d      (1'b0),
.q      (srst_tx_common  )
);

har HA2  (fs, ha, lf, c);

#need to extract xuvs
xuvs or1(fcarry_out, half_carry_2, half_carry_1);


预期产量

model_ip
native_my_ip
resync
har
xuvs


code.py

import re

input_file = open("sample.log", "r")
lines = input_file.read()   # reads all lines and store into a variable
input_file.close()
for m in re.finditer(r'^\s*([a-zA-Z_0-9]+)\s+([a-zA-Z_0-9]+\s+\(|#\()',   lines, re.MULTILINE):
   print m.group(1)

最佳答案

您需要在(之前匹配所有可选的空白字符:

^\s*(\w+)\s+(\w+|#)\s*\(
                   ^^^


请参见regex demo。可以将[a-zA-Z0-9_]缩写为\w(如果您需要在Python 3中使用它,并且仅匹配ASCII字母和数字,请使用re.ASCII标志进行编译)。

细节


^-行的开头(因为使用了re.MULTILINE
\s*-0+空格
(\w+)-组1:一个或多个字母,数字或_
\s+-1+空格
(\w+|#)-第2组:一个或多个字母,数字或_#
\s*-0+空格
\(-一个(字符。


Python demo

for m in re.finditer(r'^\s*(\w+)\s+(\w+|#)\s*\(',   lines, re.MULTILINE):
    print m.group(1)


输出:

model_ip
native_my_ip
resync
har
xuvs

10-04 22:09
查看更多