3

在下面的代码片段中,谁能解释一下是如何reg定义的?

str = "This is the first line.\n" + 
      "This is the second line.\n" + 
      "This the third line.\n";
reg = /^.*$/gm;

var mtch = str.match(reg);

需要拆分位于单独一行的三个句子,但我不明白定义拆分它的模式。

它说(我猜是这样!)字符串应该以开头并且.可以.出现多次。*当我们实际放置时需要放置global flag什么?

4

4 回答 4

3

“m”标志告诉 javascript 在换行符的开头和结尾处匹配 ^ 和 $ 锚点。因此,此正则表达式匹配包含在一行中的任何字符 0 次或更多次的所有情况(“g”标志)。

于 2013-02-24T11:42:20.123 回答
3

全局、多行匹配

g 修饰符只是意味着返回所有匹配的字符串

m 修饰符最好由文档解释:

将开始和结束字符(^ 和 $)视为处理多行(即,匹配每行的开始或结束(由 \n 或 \r 分隔),而不仅仅是整个输入字符串的开始或结束)

因此,问题中的正则表达式匹配换行符之间的所有字符串。

str = "This is the first line.\n" + 
  "This is the second line.\n" + 
  "This the third line.\n";

str.match(/^.*$/gm)
//["This is the first line.", "This is the second line.", "This the third line.", ""]

不需要 m 修饰符

开始和结束锚点实际上不是必需的。因此,一个更简单、几乎等效的正则表达式将是:

str.match(/.+/g)
//["This is the first line.", "This is the second line.", "This the third line."]

在这种情况下,.+将匹配一个或多个字符的任何字符串,不包括换行符。默认情况下,正则表达式中的匹配是贪婪的,并且会扩展以匹配最可能的匹配,因此它将字符串拆分为行。请注意,响应中没有空字符串。

这不需要正则表达式

为了这个正则表达式看起来在做什么,最好不要使用正则表达式:

str.split("\n");
//["This is the first line.", "This is the second line.", "This the third line.", ""]
于 2013-02-24T11:53:42.273 回答
1

What is the need to put * when we are actually putting the global flag ?

The * is part of the pattern (used for the match), the g is a modifier which means "all the result, not only the first one".

/^.$/m; would return a line with only one character (the first one found)

/^.*$/m; would return a line (the first one found)

/^.$/gm; would return every line with only one character

/^.*$/gm; returns every line

于 2013-02-24T12:12:35.600 回答
0

dot(.) 表示任何字符。* 表示 0 或更多。'm' 修饰符是多行的。

于 2013-02-24T11:37:10.030 回答