免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 4563 | 回复: 10
打印 上一主题 下一主题

正则表达式之{}匹配问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-11-26 17:12 |只看该作者 |倒序浏览
现在需要用正则表达式抓取{和与其相匹配的}之间的内容,但是{}里面也可能出现{和}。
例如
{hello} 抓到 hello
{hello {me}} 抓到 hello {me}
如果这样做不到的话,内容里面的{}也可以添加转义符等,比如{hello \{me\}} 抓到 hello {me}或者抓到 hello \{me\} 后再将\去掉都行.
这样的正则表达式该如何写?

论坛徽章:
0
2 [报告]
发表于 2005-11-26 21:12 |只看该作者
{}在python的正则表达式中是特殊字符,因此需要使用转义符。使用下面的语句:

import re
r = re.compile(r'\{(.*)\}')
b=r.search('asdfd{he{zzz}llo}sfsdf')
b.groups()

论坛徽章:
0
3 [报告]
发表于 2005-11-26 23:32 |只看该作者
谢谢limodou。
不过'\{(.*)\}'抓到的是第一个{和最后一个}之间的内容,而不是{和与其相匹配的}之间的内容。
比如'{hello {me}} {test}',需要抓到hello {me},用'\{(.*)\}'结果抓到的是'hello {me}} {test'。

论坛徽章:
0
4 [报告]
发表于 2005-11-26 23:59 |只看该作者
可以改为

r'\{(.*?)\}'

但对于'{hello {me}} {test}'匹配出来的就是:

'hello{me' 了。这种嵌套的不好处理。

论坛徽章:
1
荣誉会员
日期:2011-11-23 16:44:17
5 [报告]
发表于 2005-11-27 02:32 |只看该作者
原帖由 limodou 于 2005-11-26 21:12 发表
{}在python的正则表达式中是特殊字符,因此需要使用转义符。使用下面的语句:

import re
r = re.compile(r'\{(.*)\}')
b=r.search('asdfd{he{zzz}llo}sfsdf')
b.groups()

python真神奇Y

论坛徽章:
0
6 [报告]
发表于 2005-11-27 20:19 |只看该作者
神奇吗?就是正则表达式而已呀。

论坛徽章:
0
7 [报告]
发表于 2005-11-28 18:59 |只看该作者
{}前不需要\的

论坛徽章:
0
8 [报告]
发表于 2005-12-08 14:09 |只看该作者
这个有人搞出来了吗,光用正则表达式能搞出来吗?

论坛徽章:
0
9 [报告]
发表于 2005-12-08 15:57 |只看该作者

  1. import string

  2. mystring = '{hello{me}}{test}'
  3. mylist = []
  4. mywordlist = []
  5. index = mystring.find('{')
  6. mystart = index
  7. while index<len(mystring):
  8.   if mystring[index] != '}':
  9.     mylist.append(mystring[index])
  10.   else:
  11.     index_j = index
  12.     while index_j >= mystart:
  13.       mychar = mylist.pop()
  14.       index_j = index_j - 1
  15.       if mychar != '{':
  16.         mywordlist.append(mychar)
  17.       else:
  18.         mywordlist.reverse()
  19.         print string.join(mywordlist,'')
  20.         mywordlist.insert(0,'{')
  21.         mywordlist.append('}')
  22.         mywordlist.reverse()
  23.         if len(mylist)==0:
  24.           mywordlist = []
  25.         break
  26.   index = index + 1
复制代码


  1. me
  2. hello{me}
  3. test
复制代码



正则表达式我是搞不出来了,只能用这个方法了。

[ 本帖最后由 wyting 于 2005-12-8 15:58 编辑 ]

论坛徽章:
0
10 [报告]
发表于 2005-12-08 18:18 |只看该作者
现有的正则表达式估计是不行的了,不知道以后的正则表达式能不能支持计算字符出现的次数。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP