P = 'This module provides regular expression matching operations similar to those found in Perl love and'
pattern = (r'This\s[a-zA-Z\s]{1,3}expression')
M = re.findall(pattern,P)
M
以上是我的代碼,回傳表示沒有匹配到任何陳述句。
我想是通過這一段正則匹配出(This module provides regular expression)
因為現在要一個功能: 從給定的所有檔案中,我要匹配到A x x x B 或者 A x x B或者 A x B或者 A x B,(A,B,x)均為單詞
uj5u.com熱心網友回復:
pattern1 = re.compile('This(.*?)expression')
pattern2 = re.compile(r'This((\s\w+)*) expression')
pattern = re.compile('\w+')
上面的方法都有問題,你再自己測驗集中方式吧
其實你可以用空格分割字串的方式,找到你想要的結果
uj5u.com熱心網友回復:
r'This\s[a-zA-Z\s]{1,3}expression'在這段正則中[a-zA-Z\s]{1,3}指的是單個字符或空格出現1-3次,而不是某個單詞或空格出現1-3次.
試試這個行不行:
regex = r"This\s(?:\w+\s)+expression" 或 regex = r"This\s(?:\w+\s)*expression"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/188170.html
