Reputation: 51
I'm trying to create a regex for the following pattern:-
1234,4321;5678,8765;1234,4321;5678,8765;1234,4321;5678,8765;
/[0-9]+,[0-9]+;/g
or /\d+,\d+;/g
doesn't seem to work in JavaScript.
Output:-
false
function myFunction() {
var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
var patt = new RegExp(/[0-9]+,[0-9]+;/g);
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
myFunction()
<div id="demo"></div>
Upvotes: 1
Views: 82
Reputation: 51
Using the RegEx /^([0-9]+:[0-9]+,)*$/ solves the problem. ()star makes sure the pattern matches every time.
function myFunction() {
var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
var patt = new RegExp(/^([0-9]+:[0-9]+,)*$/);
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
myFunction()
<div id="demo"></div>
Upvotes: 1
Reputation: 242
Your just need one correction. i.e., pass the global flag g
as a second parameter to RegExp constructor.
function myFunction() {
var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
var patt = new RegExp(/[0-9]+,[0-9]+;/, 'g');
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
Upvotes: 1