让正则表达式变简单(PythonVerbalExpressions)

Posted Python程序员

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了让正则表达式变简单(PythonVerbalExpressions)相关的知识,希望对你有一定的参考价值。


正则表达式是编程学习过程中的一个难点, 很多人学习多年也无法精通. 昨天小编发现了一个Python库, 能够让正则表达式变得简单易用, 它就是PythonVerbalExpressions


使用案例一: 测试URL是否有效


from verbalexpressions import VerEx
# Create an example of how to test for correctly formed
URLsverbal_expression = VerEx() tester = (verbal_expression. start_of_line(). find('http'). maybe('s'). find('://'). maybe('www.'). anything_but(' '). end_of_line() )
# Create an example URL
test_url = "https://www.google.com"
# Test if the URL is valid
if tester.match(test_url):
print "Valid URL"#Print the generated regex
print tester.source() # => ^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$


使用案例二: 字符串替换


#Create a test string
replace_me = "Replace bird with a duck"

#Create an expression that looks for the word "bird"
expression = VerEx().find('bird')

#Execute the expression in VerExresult_
VerEx = expression.replace(replace_me, 'duck')
print result_VerEx

#Or we can compile and use the regular expression using re
import re regexp = expression.compile() result_re = regexp.sub('duck', replace_me)
print result_re


字符串替换的简写


result = VerEx().find('red').replace('We have a red house', 'blue')
print result


安装方法一如既往地简单


pip install VerbalExpressions


很有趣, 有兴趣的同学可以试试哦~



长按, 识别图中二维码

关注"Python程序员"


以上是关于让正则表达式变简单(PythonVerbalExpressions)的主要内容,如果未能解决你的问题,请参考以下文章