您可以将变量空白与
\s*
(零个或多个空格)或
\s+
(一个或多个空格),您可以使用
(...)
圆括号。
看着
this description of the Verilog
input
syntax
,你可以看到你会寻找
输入
后跟一个可选范围,后跟一个或多个标识符,它们是
delimited by whitespace
. 下面的模式将捕获
列表
来自这样一个语句的标识符:
r'^input\s+(?:\[[^\]]*\]\s+)?(.+);'
这个
(?:\[[^\]]*\]\s+)?
部分将匹配可选范围语法(a
[
,后跟非上的任意数字-
]
字符,后跟
]
,但没有捕获它。见
https://regex101.com/r/cT0Q0X/1
在线演示。
因为标识符总是用空格分隔的,所以可以使用
str.split()
将捕获的值转换为python列表。
您不需要将文件读入内存或使用
range
. 直接循环文件。你不需要使用
re.M
,因为您正在处理单个行。我也会放弃
re.I
,因为verilog是区分大小写的;
INPUT
不是同一件事
输入
:
with open(r'D:/pyfile/verilog.v') as file:
for line in file:
match = re.search(r'^input\s+(?:\[[^\]]*\]\s+)?(.+);', line)
if match:
identifiers = match.group(1).split()
print(*identifiers)
使用示例演示:
>>> import re
>>> from io import StringIO
>>> sample = '''\
... module(a,b,c,d, vbg
... `ifdef USE_GOOD_PIN
... , vb, vc, vd, vg ..... some more input and outputs
... `endif
... );
...
... input [7:0] t_d;
... input srd;
... output comb;
... output src;
... inout [1:0] Iout;
... output a_in;
... output b_in;
... input ff_parity;
... '''
>>> with StringIO(sample) as file:
... for line in file:
... match = re.search(r'^input\s+(?:\[[^\]]*\]\s+)?(.+);', line)
... if match:
... identifiers = match.group(1).split()
... print(*identifiers)
...
t_d
srd
ff_parity