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

2013-02-02 20:15:14 +08:00
 ooof
在 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"> 开头的行,然后替换为空。

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

谢谢!
3615 次点击
所在节点    程序员
6 条回复
scarlex
2013-02-02 23:04:00 +08:00
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
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
2013-02-03 04:23:05 +08:00
真折腾……

Notepad++中:
1. Ctrl + F, 选“Mark”(第四个Tab), 填<td rowspan="3" valign="top">,并选中“Bookmark line”
2. 菜单栏Search - Bookmark - Remove Unmarked Lines
3. Done
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
2013-02-03 11:33:55 +08:00
^(?!<td rowspan="3" valign="top">).*$
ooof
2013-02-03 13:19:47 +08:00
用 @Channing 的操作方法解决问题了。

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

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

非常感谢各位 !

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/59600

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX