stumped
stumped

Reputation: 3293

Confusion on Javascript regex with match function

Why is the third element in the array just '.1' rather than '4.5.1'? I thought that the \d+ would correspond to '3' and the (\.\d)* would capture the remaining decimals and numbers.

var re = /see (chapter \d+(\.\d)*)/i;
var str = 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3';
    
console.log(str.match(re));

Output:

[ 'see Chapter 3.4.5.1',
  'Chapter 3.4.5.1',
  '.1',
  index: 45,
  input: 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3' ]

Upvotes: 1

Views: 34

Answers (2)

Leandro Keen Zapa
Leandro Keen Zapa

Reputation: 196

array[0] is a full match
array[1] is a group match caused by a wider parenthesis (chapter \d+(\.\d)*)
array[2] is a group match caused by the narrow parenthesis  (\.\d)*

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370819

A repeated capturing group will only capture its last repetition. If you wanted to capture all of the numbers and periods, you should repeat inside the group:

var re = /see (chapter \d+((?:\.\d)*))/i;
var str = 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3';
    
console.log(str.match(re));

If you plug in your original code into regex101, you'll see a warning describing this:

https://regex101.com/r/uDTcTC/1

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

Upvotes: 2

Related Questions