免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3321 | 回复: 2

python正则表达式问题 [复制链接]

论坛徽章:
0
发表于 2014-01-13 16:50 |显示全部楼层
程序如下:
_regexp_compile_cache = {}

def Search(pattern, s):
  """Searches the string for the pattern, caching the compiled regexp."""
  if pattern not in _regexp_compile_cache:
    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  return _regexp_compile_cache[pattern].search(s)

match_point = Search(r'[^(]+([^,]*)\*([^,]*)', realine)

realine为某行的内容,程序原意为取某行含有“*”但不含有“(”的那一行,但试了下下面的两个例子
bool DimeterOmc::writeLog( int code_id, const char* log_desc, ... )
typedef bool (*DYNCHECKFUNC)();
发现都会被取出来,想问下哪里是不是写错了呢???

论坛徽章:
33
荣誉会员
日期:2011-11-23 16:44:17天秤座
日期:2014-08-26 16:18:20天秤座
日期:2014-08-29 10:12:18丑牛
日期:2014-08-29 16:06:45丑牛
日期:2014-09-03 10:28:58射手座
日期:2014-09-03 16:01:17寅虎
日期:2014-09-11 14:24:21天蝎座
日期:2014-09-17 08:33:55IT运维版块每日发帖之星
日期:2016-04-17 06:23:27操作系统版块每日发帖之星
日期:2016-04-18 06:20:00IT运维版块每日发帖之星
日期:2016-04-24 06:20:0015-16赛季CBA联赛之天津
日期:2016-05-06 12:46:59
发表于 2014-01-14 08:33 |显示全部楼层
回复 1# wuzen007
  1. r'[^(]+([^,]*)\*([^,]*)'
  2. '[^(]+'
  3. [color=Red]'([^,]*)'[/color]
  4. '\*'
  5. '[color=Red]([^,]*)[/color]'
复制代码
是红色部分匹配了 '(' 了.

如果你想不要 '(', 试试把红色的改成 [^,(] 这样

论坛徽章:
0
发表于 2014-01-14 18:15 |显示全部楼层
两个问题:
1.要匹配整行,是不是用match更合适。
match从字符串的开头开始匹配,如果开头位置没有匹配成功,就算失败了;而search会跳过开头,继续向后寻找是否有匹配的字符串。

2.正则表达式中:r'[^(]+([^,]*)\*([^,]*)' 中的[^,]是不是又包含了(
用这个试试:r'[^(]*\*+[^(]*'
  1. import re

  2. _regexp_compile_cache = {}

  3. def Search(pattern, s):
  4.   """Searches the string for the pattern, caching the compiled regexp."""
  5.   if pattern not in _regexp_compile_cache:
  6.     _regexp_compile_cache[pattern] = re.compile(pattern)
  7.   return _regexp_compile_cache[pattern].match(s)

  8. readline = 'bool DimeterOmc::writeLog( int code_id, const char* log_desc, ...)'
  9. #            typedef bool (*DYNCHECKFUNC)();'''
  10. match_point = Search(r'[^(]*\*+[^(]*', readline)

  11. print match_point.group(0)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP