简体   繁体   English

Javascript正则表达式字符串替换多行字符串

[英]Javascript regular expression string-replacement of multi-line strings

With JavaScript regular expression replace, trying to replace anything between <head> and </head> tags so that: 使用JavaScript正则表达式替换,尝试替换<head></head>标记之间的任何内容,以便:

<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. 并尝试使用非常基本的: <head(.*)\\/head>/m ,它不起作用。 It works fine when line breaks are removed from string. 当从字符串中删除换行符时,它工作正常。 No matter what type of line breaks, what's the magic? 无论什么类型的换行,什么是魔术?

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. 在大多数正则表达式中,您可以通过设置“DOTALL”或“单行”模式强制它匹配所有内容,但JavaScript不支持它。 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] (“任何空白字符或任何不是空格的字符”)。

Alan is right, to summarize, use /<head([\\s\\S]*)\\/head>/ and it should do what you wish. 总而言之,Alan是对的,使用/<head([\\s\\S]*)\\/head>/它应该按照你的意愿行事。

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 :) 我用于作业的实际正则表达式是/<head>([\\s\\S]*?)<\\/head>/但差异可能无关紧要,因为它只是确保没有贪婪的匹配永远不应该在那里的第二个头标记:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM