javascript 如何忽略正则表达式中的换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16770710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to ignore newline in regexp?
提问by Bdfy
How to ignore newline in regexp in Javascript ?
如何在 Javascript 中忽略正则表达式中的换行符?
for example:
例如:
data = "\
<test>11\n
1</test>\n\
#EXTM3U\n\
"
var reg = new RegExp( "\<" + "test" + "\>(.*?)\<\/" + "test" + "\>" )
var match = data.match(reg)
console.log(match[1])
result: undefined
结果:未定义
采纳答案by Samuel Liew
You are missing a JS newline character \
at the end of line 2.
您\
在第 2行的末尾缺少一个 JS 换行符。
Also, change regexp to:
另外,将正则表达式更改为:
var data = "\
<test>11\n\
1</test>\n\
#EXTM3U\n\
";
var reg = new RegExp(/<test>(.|\s)*<\/test>/);
var match = data.match(reg);
console.log(match[0]);
回答by t.niese
In JavaScript there is not flag to tell the RegExp that .
also should match newlines. So you need to use a workaround e.g. [\s\S]
.
在 JavaScript 中,没有标志告诉 RegExp.
也应该匹配换行符。所以你需要使用一种解决方法,例如[\s\S]
.
Your RegExp would then look this way:
然后您的 RegExp 将看起来像这样:
var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );
回答by qur2
By reading this one: How to use JavaScript regex over multiple lines?
通过阅读这篇文章:如何在多行上使用 JavaScript 正则表达式?
I came with that, which works:
我带来了,它的工作原理:
var data = "<test>11\n1</test>\n#EXTM3U\n";
reg = /<test>([\s\S]*?)<\/test>/;
var match = data.match(reg);
console.log(match[1]);
Here is a fiddle: http://jsfiddle.net/Rpkj2/
这是一个小提琴:http: //jsfiddle.net/Rpkj2/
回答by Santosh Panda
Better you can use [\s\S]
instead of . for multiline matching.
更好的是你可以使用[\s\S]
而不是 . 用于多行匹配。
It is the most common JavaScript idiom for matching everything including newlines. It's easier on the eyes and much more efficient than an alternation-based approach like (.|\n)
.
它是最常见的 JavaScript 习惯用法,用于匹配包括换行在内的所有内容。与基于交替的方法(如(.|\n)
.