python re:正則表達式中使用變量


參考:https://www.cnblogs.com/songbiao/p/12422632.html

Python中正則表達式的寫法,核心就是一個字符串。如下:re.compile(r'表達式')
所以,如果要在正則表達式中包含變量,那么就可以用{}.format語法,類似string中包含變量的處理方法,當然要確保變量為string型。如下:
re.compile(r'expression' + var + 'expression')
re.compile(r'expression(%s)expression' %var)
re.compile(r'expression{}expression'.format(var))

有用的正則表達式網頁工具和手冊:
正則表達式手冊
推薦regexr

 

參考:https://blog.csdn.net/mifaxie/article/details/79351737

正則表達寫法:
re.compile(r’表達式’)

包含變量的正則表達式寫法
re.compile(r’表達式’+變量+’表達式’)
re.compile(r’表達式(%s)表達式’ %變量)

示例代碼:

url = "oreilly.com" regex3 = re.compile(r"^((/|.)*(%s))" %url) regex4 = re.compile(r"^((/|.)*oreilly.com)") regex5 = re.compile(r"^((/|.)*"+ url +')') string3 = '/oreilly.com/baidu.com' mo3 = regex3.search(string3) mo4 = regex4.search(string3) mo5 = regex5.search(string3) print(mo3.group()) print(mo4.group()) print(mo5.group())

輸出結果如下:

/oreilly.com /oreilly.com /oreilly.com [Finished in 1.3s]

參考:https://www.cnblogs.com/Atanisi/p/8536046.html

我們有時想把變量放進正則表達式中來匹配想要的結果。Python中使用 re.compile(r''+變量+''),其中正則表達式中的“變量”應為字符串形式。

1 import re
2 regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([.\deE+-]+)')
3 regex_test_output

  得到結果

re. compile (r 'Test net output #(\d+): (\S+) = ([.\deE+-]+)' , re. UNICODE )

  可以看到,Python是將正則表達式用字符串表示的,格式為 r'正則表達式 '

  正則表達式使用變量例子:

1 regex_test = []
2 for i in range(5):
3     regex_test.append(re.compile(r'Iteration (\d+), Testing net \(#' + str(i) + '\)'))
4     print(regex_test[i])

  結果為

re. compile ( 'Iteration (\\d+), Testing net \\(#0\\)' )
re. compile ( 'Iteration (\\d+), Testing net \\(#1\\)' )
re. compile ( 'Iteration (\\d+), Testing net \\(#2\\)' )
re. compile ( 'Iteration (\\d+), Testing net \\(#3\\)' )
re. compile ( 'Iteration (\\d+), Testing net \\(#4\\)' )

附正則表達式語法:網址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM