简体   繁体   中英

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.

Thank you!

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM