I'm having a problem with my regex.
var validFormat = /^(JD[a-zA-Z0-9]{6}),(.*),(.*)$/;
console.log('JD231SSD, First Name, Last Name'.match(validFormat));
This will result in
["JD231SSD, First Name, Last Name", "JD231SSD", " First Name", " Last Name", index: 0, input: "JD231SSD, First Name, Last Name"]
and this is OK, but the first name and last name are optional so what I want to achieved are following to be valid.
'JD231SSD, First Name'
'JD231SSD'
So I can get the following:
["JD231SSD, First Name", "JD231SSD", " First Name", index: 0, input: "JD231SSD, First Name"]
["JD231SSD", "JD231SSD", index: 0, input: "JD231SSD"]
I was hoping that I could achieved this using regex but I'm not sure if it's possible. Because if it's not then I can try another solution.
4 Answers 4
var validFormat = /^(JD[a-zA-Z0-9]{6}),?([^,]*),?([^,]*)$/;
Comments
You may use
^(JD[a-zA-Z0-9]{6})(?:,([^,\n]*))?(?:,([^,\n]*))?$
See demo
The \n is not necessary if the strings do not contain newlines.
I replaced the (.*) with negated class [^,] and added optional non-capturing group ((?: ... )?) around comma + [^,].
var re = /^(JD[a-zA-Z0-9]{6})(?:,([^,\n]*))?(?:,([^,\n]*))?$/gm;
var str = 'JD231SSD, First Name, Last Name\nJD231SSD, First Name\nJD231SSD';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
document.write("Whole match: " + m[0] + "<br/>");
document.write("ID: " + m[1] + "<br/>");
if (m[2] !== undefined) {
document.write("First name: " + m[2] + "<br/>");
}
if (m[3] !== undefined) {
document.write("Last name: " + m[3] + "<br/>");
}
document.write("<br/>");
}
2 Comments
$?? You should use it exactly as it is in my answer.^(JD[a-zA-Z0-9]{6})(?:,(.*?)(?:,(.*))?)?$
You can use this regex to capture all three.See demo.
Comments
var validFormat = ^(JD[a-zA-Z0-9]{6})(?:,(.*?)(?:,(.*))?)?$;
console.log('JD231SSD, First Name, Last Name'.match(validFormat));
'JD231SSD, John'is john is a first name or last name?JD123SSD, John, Homestead, of theandJD123SSD, MaryandJD123SSD, Marc-Anthony, d'Artagnanand... (Check out this article for some more fun possibilities...)