1

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' ]
0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0
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)*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.