JavaScript Regex Failure Analysis
When encountering null results from JavaScript regexes, it's important to delve into the intricacies behind the expression. Let's examine why a specific regex for extracting coordinates from a comma-separated string yielded no matches:
Regex construction flaws:
The regex in question was defined as:
new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g")
Instead, a regex literal should have been used:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
Regex Output Analysis:
To better understand the regex, one can output its pattern using the console:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
This reveals that the expression will match literals 's', 'g', and parens literally, which is not the intended behavior.
Array Output Considerations:
It's crucial to note that match() returns an array of matches:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
To extract the individual numbers, exec() should be used instead:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]
The unary plus operator ( ) can then be used to convert strings to numbers.
Complete Code:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g; var result, points = []; while((result = reg.exec(polygons)) !== null) { points.push([+result[1], +result[2]]); }
This code will create an array of arrays containing the extracted coordinates as numbers.
The above is the detailed content of Why Are My JavaScript Regexes Failing to Extract Coordinates?. For more information, please follow other related articles on the PHP Chinese website!