最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript regular expression string-replacement of multi-line strings - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share edited Jan 19, 2011 at 13:01 SilentGhost 320k67 gold badges310 silver badges294 bronze badges asked Jan 19, 2011 at 11:10 Rushen BilginRushen Bilgin 511 silver badge4 bronze badges 1
  • see blog.stevenlevithan./archives/singleline-multiline-confusing – endolith Commented Jun 7, 2012 at 19:25
Add a ment  | 

2 Answers 2

Reset to default 8

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 mon idiom is [\s\S] ("any whitespace character or any character that's not whitespace").

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 :)

发布评论

评论列表(0)

  1. 暂无评论