gpt4 book ai didi

python - 使用 Python 和正则表达式在字符串中查找 C 关键字

转载 作者:行者123 更新时间:2023-11-28 21:15:30 25 4
gpt4 key购买 nike

我正在尝试查找并打印字符串中 C 关键字的开始和结束索引

code = 'int main( void )\n{\nreturn 0;\n}'

这是我目前所拥有的:

pattern = '/\bint|void|return\b/'
temp = re.compile( pattern )
for result in temp.finditer( code ):
print 'Found %s from %d to %d.' % ( result.group(), result.start(), result.end() )

但是,只找到了'void'。这是为什么?

最佳答案

这是一个例子:

src='''\
int main( void )
{
return 0;
}
'''

import re

for key, span in ((m.group(1), m.span(1)) for m in re.finditer(r'\b(int|main|void|return)\b', src)):
print key, span

打印:

int (0, 3)
main (4, 8)
void (10, 14)
return (28, 34)

但我认为使用一组关键字来验证找到的词比将所有词都放在一个模式中更好。

考虑:

keywords={'int', 'main', 'void', 'return'}

for key, span in ((m.group(1), m.span(1)) for m in re.finditer(r'\b(\w+)\b', src)
if m.group(1) in keywords):
print key, span

相同的输出,但更容易添加单词。

关于python - 使用 Python 和正则表达式在字符串中查找 C 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com