正则表达式中(?:)的巨大作用
生活随笔
收集整理的這篇文章主要介紹了
正则表达式中(?:)的巨大作用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
理論上的解釋:
1、其中?:的作用是匹配Swift3模式字符串,但不會存儲該匹配。
2、It's called a 'non-capturing group', which means the regex would?not?make a group by the match inside the parenteses like it would otherwise do (normally, a parenthesis creates a group)
3、When you use?(?:)?it means that the?group?is matched but is not captured for back-referencing i.e?non-capturing?group. It's not stored in memory to be referenced later on.
實際的效果:
import re y= '123@qq.comaaa@163.combbb@126.comasdfasfs33333@adfcom' #第一種寫法: ret1=re.findall('[0-9a-z]+@+[0-9a-z]+\.com',y) print(ret1) ##第二種寫法: ret2=re.findall('(\w+@(qq|126|163)\.com)',y) #for i in ret2: # print(i[0]) print(ret2) #第三種寫法: ret3=re.findall('\w+@(?:qq|126|163)\.com',y) print(ret3)#第四種寫法: ret3=re.findall('\w+@(qq|126|163)\.com',y) print(ret3)#第五種寫法: ret3=re.findall('(\w+@(?:qq|126|163)\.com)',y) print(ret3)輸出結果:['123@qq.com', 'aaa@163.com', 'bbb@126.com'] [('123@qq.com', 'qq'), ('aaa@163.com', '163'), ('bbb@126.com', '126')] ['123@qq.com', 'aaa@163.com', 'bbb@126.com'] ['qq', '163', '126'] ['123@qq.com', 'aaa@163.com', 'bbb@126.com']結論:
1、匹配多個字符串中其中一個的方法是使用是小括號+"|",而不是我認為的[http|www],而應該是(http|www)
2、由于findall會返回所有括號內的內容,而我本意只是個約束條件;這個時候可以加上? "?:"?
總結
以上是生活随笔為你收集整理的正则表达式中(?:)的巨大作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 加速数据分析,这12种高效Numpy和P
- 下一篇: collection包下Counter类