鱼C论坛

 找回密码
 立即注册
查看: 707|回复: 6

[已解决]正则表达式

[复制链接]
发表于 2019-5-27 17:16:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> p = re.compile(r'(\b\w+)\s+\1')
>>> p.search('Paris in the the spring').group()
'the the'


问题:  能不能解释这个表达式,看不太懂。 尤其是\1
最佳答案
2019-5-28 08:23:26
  1. import re

  2. p = re.compile(r'(\b\w+)\s+\1')
  3. print(p.search('Paris in the the spring').group())
  4. '''  
  5.     \b 单词分界符\b  
  6.     \w  代表是大小写字母,10个数字和下划线 这里是是英文字母
  7.     \1,\2…的元字符序列表示前面捕获性括号内的字串(块),”\1”叫反向引用
  8.     \s  任意一个不可见字符,\n\t\r和空格等等  
  9. '''
  10. #稍微严禁一下
  11. p = re.compile(r'\b(\w+)\b\s+\1')
  12. print(p.search('Paris in the the spring').group())

  13. #灵活一下 1
  14. p = re.compile(r'(\w+)\s+\1')
  15. print(p.search('Paris in the the spring').group())

  16. #灵活一下 2
  17. p = re.compile(r'(\w+)\s+\1')
  18. print(p.findall('Paris in the the spring 123 123 abc'))
  19. #['the', '123']
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-5-27 19:33:00 | 显示全部楼层
\number   表示匹配分组的第number个子表达式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-27 20:32:13 | 显示全部楼层
p = re.compile(r'(\b\w+)\s+\1')


(\b\w+) 表示匹配一个单词 , \s表示匹配任意空白字符,这里表示空格 , \1 表示重复分组里面的匹配内容

这里只有 the the 符合满足这个条件,故返回结果为the the
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-28 08:23:26 | 显示全部楼层    本楼为最佳答案   
  1. import re

  2. p = re.compile(r'(\b\w+)\s+\1')
  3. print(p.search('Paris in the the spring').group())
  4. '''  
  5.     \b 单词分界符\b  
  6.     \w  代表是大小写字母,10个数字和下划线 这里是是英文字母
  7.     \1,\2…的元字符序列表示前面捕获性括号内的字串(块),”\1”叫反向引用
  8.     \s  任意一个不可见字符,\n\t\r和空格等等  
  9. '''
  10. #稍微严禁一下
  11. p = re.compile(r'\b(\w+)\b\s+\1')
  12. print(p.search('Paris in the the spring').group())

  13. #灵活一下 1
  14. p = re.compile(r'(\w+)\s+\1')
  15. print(p.search('Paris in the the spring').group())

  16. #灵活一下 2
  17. p = re.compile(r'(\w+)\s+\1')
  18. print(p.findall('Paris in the the spring 123 123 abc'))
  19. #['the', '123']
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-28 08:28:30 | 显示全部楼层
1.jpg
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-6-8 09:12:35 | 显示全部楼层

\1 , 这里是只能匹配和前一次匹配相同的单词么。不然为什么只能匹配单词the?
灵活2 里面的返回值为啥只有一个 the 和一个123 呀?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-8 12:28:54 | 显示全部楼层
import re

s='Paris in the the spring 123  123 abc'
#灵活一下 2
p = re.compile(r'(\w+)\s+\1')
print(p.findall(s))
#['the', '123']
print(p.search(s).group())
#the the

print('-'*20)
re.sub(r'(\w+)\s+\1',lambda i:print(i.group()),s)
#the the
#123  123
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-13 02:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表