我有一堆带有这样行的html:
<a href="#" rel="this is a test">
我需要用下划线替换 rel 属性中的空格,但我有点像 regex-noob!
我正在使用 Textmate。
谁能帮我?
/雅各布
寻找:(rel="[^\s"]*)\s([^"]*")
代替:\1_\2
这只会替换第一个空格,因此单击“全部替换”,直到不再替换任何内容。它并不漂亮但易于理解并且适用于每个编辑器。
rel
如果您需要清除其他属性,请更改查找模式。
假设你已经收到了 rel 的值:
var value = document.getElementById(id).getAttribute( "rel");
var rel = (new String( value)).replace( /\s/g,"_");
document.getElementById(id).setAttribute( "rel", rel);
我认为你不能正确地做到这一点。虽然我想知道为什么你需要一次性完成?
我可以想到一个非常糟糕的方法,但即使我不推荐它,这里是:
你可以用下面的正则表达式来做。但是,您必须将捕获和输出的数量与 _ 结尾增加到 rel 中的潜在空格数。我敢打赌,这是不允许此解决方案的要求。
搜索:
{\<a *href\=\"[^\"]*" *rel\=\"}{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*{([^ ]*|[^\"]*)}( |\")*
代替:
\1\2_\3_\4_\5_\6_\7_\8_
这种方式有两个缺点,一个是您可以在 Textmate 中捕获的数量可能会受到限制,二是您最终会在每行的末尾有大量的 _。
通过您当前的测试,使用上面的正则表达式,您最终会得到:
<a href="#" rel="this_is_a_test">____
PS:这个正则表达式是 Visual Studio 搜索/替换框的格式。您可能需要更改一些字符以使其适合文本板。
{} => capturing group
() => grouping
[^A] => anything but A
( |\")* => space or "
\1 => is the first capture
正则表达式根本不擅长解析 HTML(请参阅您能否提供一些示例,说明为什么用正则表达式解析 XML 和 HTML 很困难?为什么)。您需要的是一个 HTML 解析器。请参阅您能否提供一个使用您最喜欢的解析器解析 HTML 的示例?对于使用各种解析器的示例。
我必须在这里接受“你使用错误的工具来完成工作”的培训。你有 Textmate,这意味着 OSX,这意味着你有 sed、awk、ruby 和 perl,它们都可以做得更好、更容易。
学习如何使用其中一种工具进行文本操作将在未来为您带来数不胜数的好处。这是一个可以让您轻松进入 sed 的 URL:http: //www.grymoire.com/Unix/Sed.html
如果您使用的是 TextMate,那么您使用的是 Mac,因此使用的是 Python。
试试这个:
#!/usr/bin/env python
import re
input = open('test.html', 'r')
p_spaces = re.compile(r'^.*rel="[^"]+".*$')
for line in input:
matches = p_spaces.findall(line)
for match in matches:
new_rel = match.replace(' ', '_')
line = line.replace(match, new_rel)
print line,
样本输出:
$ cat test.html
testing, testing, 1, 2, 3
<a href="#" rel="this is a test">
<unrelated line>
Stuff
<a href="#" rel="this is not a test">
<a href="#" rel="this is not a test" rel="this is invalid syntax (two rels)">
aoseuaoeua
$ ./test.py
testing, testing, 1, 2, 3
<a_href="#"_rel="this_is_a_test">
<unrelated line>
Stuff
<a_href="#"_rel="this_is_not_a_test">
<a_href="#"_rel="this_is_not_a_test"_rel="this_is_invalid_syntax_(two_rels)">
aoseuaoeua