kdlcruz
kdlcruz

Reputation: 1388

Regex Matching using Javascript

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.

Upvotes: 1

Views: 82

Answers (4)

I A Khan
I A Khan

Reputation: 8869

var validFormat = ^(JD[a-zA-Z0-9]{6})(?:,(.*?)(?:,(.*))?)?$;
console.log('JD231SSD, First Name, Last Name'.match(validFormat));

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

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/>");
    
}

Upvotes: 1

h3n
h3n

Reputation: 898

var validFormat = /^(JD[a-zA-Z0-9]{6}),?([^,]*),?([^,]*)$/;

Upvotes: 2

vks
vks

Reputation: 67988

^(JD[a-zA-Z0-9]{6})(?:,(.*?)(?:,(.*))?)?$

You can use this regex to capture all three.See demo.

https://regex101.com/r/uF4oY4/80

Upvotes: 1

Related Questions