V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ooof
V2EX  ›  程序员

求解一个正则表达式的问题

  •  
  •   ooof ·
    ooof · 2013-02-02 20:15:14 +08:00 · 3570 次点击
    这是一个创建于 4094 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在 Notepad++ 中,想只保留这样的行: <td rowspan="3" valign="top"><a href="user.php?id=Oficial_Regii"><img border="0" width="48px" height="48px" src="http://a0.twimg.com/profile_images/3055970391/a276aa65a36df44126247c8972f8144c_normal.jpeg" title="ReGina Official" /></a></td>

    想到用正则表达式匹配不是 <td rowspan="3" valign="top"> 开头的行,然后替换为空。

    但不知道这个正则表达式该怎么写,求助。

    谢谢!
    6 条回复    1970-01-01 08:00:00 +08:00
    scarlex
        1
    scarlex  
       2013-02-02 23:04:00 +08:00   ❤️ 1
    python的话,直接re.search(pattern, string)就行了~
    python code:
    --------------------------------------------------------------------
    import re
    f = open('test.txt', 'r')
    s = open('after_re.txt', 'w')
    pattern = r'<td rowspan="3" valign="top">.*'
    for i in f.readlines():
    print i
    match = re.search(pattern, i)
    try:
    mystring = match.group(0)
    s.write(mystring)
    except:
    pass
    --------------------------------------------------------------------
    ooof
        2
    ooof  
    OP
       2013-02-03 01:19:27 +08:00
    import re
    f = open('c:\\t.html', 'r')
    s = open('c:\\after_re.txt', 'w')
    pattern = r'<td>.*'
    for i in f.readlines():
    print i
    match = re.search(pattern, i)
    try:
    mystring = match.group(0)
    s.write(mystring)
    except:
    pass

    改了一下,执行完, after_re.txt 怎么还是为空啊?
    Channing
        3
    Channing  
       2013-02-03 04:23:05 +08:00   ❤️ 2
    真折腾……

    Notepad++中:
    1. Ctrl + F, 选“Mark”(第四个Tab), 填<td rowspan="3" valign="top">,并选中“Bookmark line”
    2. 菜单栏Search - Bookmark - Remove Unmarked Lines
    3. Done
    scarlex
        4
    scarlex  
       2013-02-03 09:00:32 +08:00
    @ooof
    你文件里没有<td>标签吧...
    我们的匹配样式是pattern = r'<td>.*',它匹配的是以<td>开头的一行。
    如果你的<td>标签里定义了其他属性,那么就改一下匹配样式吧~

    另外,可以在match = re.search(pattern, i)的下一行增加一句print match
    看看有没有返回Match对象,如果全部是None,那么你的文件里就没有<td>....
    weizhenye
        5
    weizhenye  
       2013-02-03 11:33:55 +08:00
    ^(?!<td rowspan="3" valign="top">).*$
    ooof
        6
    ooof  
    OP
       2013-02-03 13:19:47 +08:00
    用 @Channing 的操作方法解决问题了。

    其它的方法也要学习一下。

    总是在摸索和尝试上用了很多时间,而忽视了系统的学习和思考,这也是需要反思的地方。

    非常感谢各位 !
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2934 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 03:43 · PVG 11:43 · LAX 20:43 · JFK 23:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.