简体   繁体   English

javascript正则表达式的结果无法理解

[英]Result of javascript regular expression not understood

When I eval (in javascript) [I meant, used string.match()]: 当我评估(在javascript中)[我的意思是,使用string.match()]:

<!--:es-->Text number 1<!--:--><!--:en-->text 2<!--:-->

using 使用

/<!--:es-->(.|\n)*?<!--:-->/

I get as match: 我得到了比赛:

Text number 1,1

I mean, it adds a comma and repeats the last character. 我的意思是,它添加了一个逗号并重复了最后一个字符。 Does anybody know why this happens? 有人知道为什么会这样吗?

PS. PS。 text could have carriage return, that is why i used (.|\\n). 文本可能有回车符,这就是为什么我使用(.|\\n).

Thanks a lot. 非常感谢。

The result of a regular expression match is an array. 正则表达式匹配的结果是一个数组。

The zero-th element of the array is the whole match : "Text number 1" The first element of the array is the contents of the first group, in this case "1" since the * is outside the parentheses. 数组的第零个元素是整体匹配项:“文本号1”数组的第一个元素是第一组的内容,在本例中为“ 1”,因为*在括号之外。

When the array is converted to a string, you get the contents with commas in between. 将数组转换为字符串时,将在内容之间加上逗号。

When I eval (in javascript) 当我评估(在javascript中)

Don't. 别。 Use RegExp 使用RegExp

Eval() evaluates any ECMAScript, you don't want to do this if you don't have 100% control over the input. Eval()会评估任何ECMAScript,如果您对输入没有100%的控制,则不要执行此操作。

Some research has shown me that the . 一些研究表明我知道. can't match newlines in javascript. 不能在javascript中匹配换行符。

I'd rewrite your regex this way: 我会这样重写您的正则表达式:

/<!--:es-->[\\s\\S]*?<!--:-->/

This will avoid the problem you saw, as it excludes the capture group. 这样可以避免您看到的问题,因为它排除了捕获组。

And ghoppe is right: use RegExp. ghoppe是正确的:使用RegExp。

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

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