使用python正则表达式查找重复表达式
您好,我正在尝试从文件中检索以下字符串。
neighbors= {5 7 9 11 13 14 15 16 17 }
模式 {number1 number2... }
各不相同,有些很短,有些太长。我想找到这样的模式。我的逻辑是检索语句 "neighbors= {"
,后面跟着一个数字和一个空格作为重复,直到程序找到最后一个右大括号。有人可以帮我解决语法问题吗?
谢谢
Hello I am trying to retrieve the following string from a file
neighbors= {5 7 9 11 13 14 15 16 17 }
The pattern {number1 number2... }
varies, some are short some are too long. I want to find such a pattern. My logic is to retrieve the statement "neighbors= {"
which is followed by a number and a space as a repetition till the program finds the last closed braces. Can some one help me out with the syntax?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你正在寻找这个:
正则表达式是可移植的,当然可以移植到许多不同的语言。
运行会产生...
但是正则表达式将匹配大括号中的任意数量的数字。
编辑
用
re.findall()
和re.compile()
进行说明...运行第二个代码返回...
尽管您应该记住
.findall( )
用于在目标字符串中多次出现正则表达式匹配。提供的示例并未说明需要.findall()
I think you're looking for this:
The regex is portable, of-course to many different languages.
Running that yields...
But the regex will match an arbitrary number of digits in curly-braces.
EDIT
Illustrating with
re.findall()
andre.compile()
...Running the second code returns...
Although you should remember that
.findall()
was meant for multiple occurrences of the regex match inside a target string. The examples provided have not illustrated a need for.findall()
我会取出带有“neighbors”一词的整行,提取大括号之间的字符串,用空格分隔,然后我将得到一个可以转换为整数的字符串数组
I would take the whole line with the word neighbors in it, extract the string that's between the braces, split by space and then I'd have an array of strings which can be converted to integers
这就是您所要求的:
使其更能容忍 {} 小括号周围的一些可选空格:
或更短的空格:
this is about what you asked for:
making it more tolerant to some optional spaces around the {} brakets:
or a shorter one: