Javascript正则表达式字符串-多行字符串的替换
使用 JavaScript 正则表达式替换,尝试替换 和
标记之间的任何内容,以便:
<head>
Multiline foo
</head>
<body>
Multi line bar
</body>
被替换为:
<body>
Multi line bar
</body>
并尝试使用非常基本的: /m
不起作用。当从字符串中删除换行符时,它可以正常工作。不管什么类型的换行符,有什么魔力呢?
With JavaScript regular expression replace, trying to replace anything between <head>
and </head>
tags so that:
<head>
Multiline foo
</head>
<body>
Multi line bar
</body>
gets replaced into:
<body>
Multi line bar
</body>
and trying with the very basic: <head(.*)\/head>/m
which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是点元字符与换行符不匹配。在大多数正则表达式风格中,您可以通过设置“DOTALL”或“单行”模式来强制它匹配所有内容,但 JavaScript 不支持这一点。相反,您必须用确实匹配所有内容的内容替换点。最常见的习惯用法是
[\s\S]
(“任何空白字符或任何非空白字符”)。The problem is that the dot metacharacter doesn't match newlines. In most regex flavors you can force it to match everything by setting "DOTALL" or "single-line" mode, but JavaScript doesn't support that. Instead, you have to replace the dot with something that does match everything. The most common idiom is
[\s\S]
("any whitespace character or any character that's not whitespace").艾伦是对的,总结一下,使用
//
它应该做你想做的事。我用于这项工作的实际正则表达式是
/([\s\S]*?)<\/head>/
但差异可能并不重要,因为它只是确保不存在与永远不应该存在的第二个头标签的贪婪匹配:)Alan is right, to summarize, use
/<head([\s\S]*)\/head>/
and it should do what you wish.The actual regex i'd use for the job is
/<head>([\s\S]*?)<\/head>/
but the difference probably won't matter, since it just assures there is no greedy matching with a 2nd head tag that should never be there :)