Javascript Regex (x,y) Match multiple
I am newbie to Javascript.
What regex will be used to match the following expression type. Please note that there could be s开发者_如何学Pythonpaces between digits.
(3,2), ( 2,3),(5, 4)
I am trying as (\d+,\d) but this is not working for multiple pairs of (x,y).
See the RE below: \s*
means: "any whitespace". The parentheses have a special meaning, and have to be escaped.
The first RE just matches all pairs of numbers, while the second RE also group the numbers, so that they can be referred when using the RegExp.exec
function.
/\(\s*\d+\s*,\s*\d+\s*\)/g
/\(\s*(\d+)\s*,\s*(\d+)\s*\)/g
Example, get all (x,y) pairs within a string, and store the pair in an array:
var source = "(1,2), (3,4) (5,6) (7,8)"; //Comma between pairs is optional
var RE = /\(\s*(\d+)\s*,\s*(\d+)\s*\)/g, pair;
var pairList = [];
while((pair = RE.exec(source)) !== null){
pairList.push([pair[1], pair[2]]);
}
//pairList is an array which consists all x,y pairs
this should match (x,y),(v,w) like patterns. 0 to n (x,y), expresions plus 1 (x,y) expresion (including whitespaces)
/(\(\s*\d+\s*,\s*\d+\s*\),\s*)*\(\s*\d+\s*,\s*\d+\s*\)/
Try this code:
patt = RegExp('\(\s*\d*\s*,\s*\d*\s*\),{0,1}', 'g')
patt.test("(3,2), ( 2,3),(5, 4)") => true
You can try this /(\(\d+\s*,\s*\d+\)*)/g.exec('(2,3), (3,4)')
or using the string at the start '(2,3), (3,4)'.match(/(\(\d+\s*,\s*\d+\)*)/g)
精彩评论