Matching multiline Patterns

匆匆过客 提交于 2019-11-28 10:08:09

问题


I want to use greasemonkey to scrape wiki data from Last.fm (this is not possible with their REST api). I can grab the page fine with GM_xmlhttpRequest(), and it is returning properly.

I do not want to use a DOM processor to process the whole page, since I only want a small chunk, so I'm using regular expressions.

The wiki data is in the page like:

<div id="wiki">
description

description
...
</div>

So I wrote:

/\<div id="wiki"\>(.+)\<\/div\>/m.exec(data)[1];

When I test this in error console (where the multiple lines are flattened into a single line, it works, but on the page it fails and says

Error: /\<div id="wiki"\>(.+)\<\/div\>/m.exec(data) is null
Source File: file:///home/jeff/.mozilla/firefox/x4su9596.default/extensions/%7Be4a8a97b-f2ed-450b-b12d-ee082ba24781%7D/components/greasemonkey.js
Line: 357

I am guessing that multiline mode does not make dor match new lines, which is what I expected. How do I make it match any character including line breaks?


回答1:


The dot doesn't match newlines in javascript -- a quirk of js's regex flavor.

[^] should work instead (e.g. "Everything except absolutely nothing")




回答2:


try [\s\S], because [^] doesn't work in IE8




回答3:


Try (.*?) instead of (.+)



来源:https://stackoverflow.com/questions/1387116/matching-multiline-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!