简体   繁体   English

无法理解javascript的正则表达式的工作方式

[英]Can't make sense of the way javascript's regex works

Why does this code ( here's the JSBin ): 为什么这个代码( 这里是JSBin ):

var text = "T: 01202 870738";

var regex1 = /T: (.*)/;
var matches1 = text.match(regex1);

for(var i = 0; i < matches1.length; i++) {
  log("[" + i + "]: " + matches1[i]);
}

logs this: 记录这个:

[0]: T: 01202 870738
[1]: 01202 870738

and this code (note I've added the g option): 和这段代码(注意我添加了g选项):

var regex2 = /T: (.*)/g;
var matches2 = text.match(regex2);

for(var i = 0; i < matches2.length; i++) {
  log("[" + i + "]: " + matches2[i]);
}

logs this: 记录这个:

[0]: T: 01202 870738

I actually don't even understand why is the first code logging 01202 870738 as the second match. 我实际上甚至不明白为什么第一个代码记录01202 870738作为第二个匹配。 How is that a match for /T: (.*)/ if it doesn't include a T: ? 如果它不包含T:那么/T: (.*)/匹配怎么样?

The second one is a global regular expression, so the array returned is a list of all the matches for the expression in the string. 第二个是全局正则表达式,因此返回的数组是字符串中表达式的所有匹配项的列表。 The first one isn't, so it's a list of groups, like you would get from exec . 第一个不是,所以这是一个组列表,就像你从exec那里得到的那样。 (Group zero being the entire match, and group one being the only parenthesized... group.) (第0组是整个匹配,第1组是唯一的括号...组。)

What throws you off is the different behavior you get from a regex with and without the g flag. 让你失望的是你在带有和没有g标志的正则表达式中获得的不同行为。 Calling String.match with a g flagged regex will return an array of all instances of the pattern within the String object. 使用带有g标记的正则表达式调用String.match将返回String对象中所有模式实例的数组。 For example, the expression: 例如,表达式:

"Hello World!".match(/l/g);

Will return this array: 将返回此数组:

["l", "l", "l"]

However, calling the same function without the g flag will return an array whose first element is the matched pattern. 但是,在没有g标志的情况下调用相同的函数将返回一个数组,其第一个元素是匹配的模式。 Any element thereafter will match each expression within parentheses. 此后的任何元素都将匹配括号内的每个表达式。 For example, the expression: 例如,表达式:

"Hello World!".match(/(Hell)o World(!)/);

Will conveniently return this array: 将方便地返回此数组:

["Hello World!", "Hell", "!"]

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

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