I am just getting started with regex in JavaScript (and in general) and I have come across an oddity that I can’t seem to find an explanation for using Google.
Without getting into to much detail, I am using the following expression:
/(^sw:\s?(-?\d{1,3}.\d{1,6})\sne:\s?(-?\d{1,3}.\d{1,6})$)/i
Which is matching user input like:
sw: -27.990344 ne: 150.234562
With the following console.log output:
["sw: -27.345455 ne: 180.234567", "sw: -27.345455 ne: 180.234567", "-27.345455", "180.234567"]
0 "sw: -27.345455 ne: 180.234567"
1 "sw: -27.345455 ne: 180.234567"
2 "-27.345455"
3 "180.234567"
index 0
input "sw: -27.345455 ne: 180.234567"
My Question is: Why is index 0 and 1 returning the user supplied input and the actual data I would like is return as index 2 and 3?
I assume its relative to my expression, but don’t know enough about it to be sure its not just normal behaviour.
Any help appreciated.
Index 0 is always the complete match, the capturing groups are starting at index 1.
The capturing groups are numbered by their opening brackets, first opening bracket is group 1, second opening bracket is group 2, …
You have brackets around your complete expression, so this is the first capturing group. ==> This outer brackets are not needed, you can remove them and then your groups will start at index 1.
For more information about capturing groups you can have a look at /www.regular-expressions.info, this is a very good resource about regexes.