如何在多行上使用JavaScript正则表达式? [英] How to use JavaScript regex over multiple lines?

查看:159
本文介绍了如何在多行上使用JavaScript正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";
var arr= ss.match( /<pre.*?<\/pre>/gm );
alert(arr);     // null

我想要接收PRE块,即使它跨越换行符。我以为'米'旗就是这么做的。没有。

I'd want the PRE block be picked up, even though it spans over newline characters. I thought the 'm' flag does it. Does not.

找到答案 here 发布前。我以为我认识JavaScript(读了三本书,工作了几个小时),而且现在没有现成的解决方案,我敢于发帖。 扔石头

Found the answer here before posting. SInce I thought I knew JavaScript (read three books, worked hours) and there wasn't an existing solution at SO, I'll dare to post anyways. throw stones here

所以解决方案是:

var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";
var arr= ss.match( /<pre[\s\S]*?<\/pre>/gm );
alert(arr);     // <pre>...</pre> :)

有没有人有一种不那么神秘的方式?

Does anyone have a less cryptic way?

编辑:这个是重复的,但由于它比我的更难找到,我不知道t删除。

this is a duplicate but since it's harder to find than mine, I don't remove.

它建议 [^] 作为多线点。我仍然不明白为什么 [。\ n] 不起作用。猜猜这是JavaScript的一个令人伤心的部分..

It proposes [^] as a "multiline dot". What I still don't understand is why [.\n] does not work. Guess this is one of the sad parts of JavaScript..

推荐答案

[。\ n] 不起作用,因为 [] 中没有特殊含义,它只是意味着文字(。| \ n)将是一种指定任何字符,包括换行符的方法。如果您想匹配所有换行符,您还需要添加 \ r 以包含Windows和经典Mac OS样式行结尾:(。 | [\\\\ n])

[.\n] does not work because . has no special meaning inside of [], it just means a literal .. (.|\n) would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r as well to include Windows and classic Mac OS style line endings: (.|[\r\n]).

事实证明这有点麻烦,而且很慢(参见 KrisWebDev的详细答案),所以更好的方法是匹配所有空白字符和所有非空白字符, [\\\\ S] ,它将匹配所有内容,并且更快更简单。

That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S], which will match everything, and is faster and simpler.

一般来说,你不应该尝试使用正则表达式来匹配实际的HTML标记。例如,参见这些 问题有关原因的更多信息。

In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.

相反,尝试实际搜索DOM以获取所需的标记(使用jQuery使这更容易,但您可以随时使用标准DOM执行 document.getElementsByTagName(pre),然后使用正则表达式搜索这些结果的文本内容,如果您需要匹配内容。

Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre") with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.

这篇关于如何在多行上使用JavaScript正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆