从全局表达式创建正则表达式 [英] Create regex from glob expression
本文介绍了从全局表达式创建正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了使用正则表达式解析文本的程序.正则表达式应从用户那里获取.我不愿意使用glob语法进行用户输入,并在内部将glob字符串转换为正则表达式.例如:
i write program that parse text with regular expression. Regular expression should be obtained from user. I deside to use glob syntax for user input, and convert glob string to the regular expression internally. For example:
"foo.? bar*"
应转换为
"^.*foo\.\w\bar\w+.*"
以某种方式,我需要从字符串中转义所有有意义的字符,然后我需要替换glob *和?带有正则表达式语法的字符.最方便的方法是什么?
Somehow, i need to escape all meaningful characters from the string, then i need to replace glob * and ? characters with apropriate regexp syntax. What is the most convinient way to do this?
推荐答案
不需要不完整或不可靠的黑客手段. python包含了一个为此功能的功能
no need for incomplete or unreliable hacks. there's a function included with python for this
>>> import fnmatch
>>> fnmatch.translate( '*.foo' )
'.*\\.foo$'
>>> fnmatch.translate( '[a-z]*.txt' )
'[a-z].*\\.txt$'
这篇关于从全局表达式创建正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文