【发布时间】:2016-12-03 01:45:09
【问题描述】:
我需要用 JavaScript 解析一个逗号分隔的字符串。该字符串是从 CSV 文件中提取的。字符串将被 \r\n、\n 或 \r 分割。第一行是标题。
var str = 'firstname,middlename,lastname,address1,address2,city,st,zip,Custom01,Custom02,Custom03,Custom04,Custom05,Custom06,Custom07,Custom08,Custom09,Custom10,Custom11,Custom12,Custom13,Custom14,Custom15,Custom16,Custom17,Custom18,Custom19,Custom20 \n K,,P,123 ST,,CENTENNIAL,CO,80122-3011,,,,,,,,,,,,,,,,,,,, \n K,,P,123 ST,,AURORA,CO,80013-2355,,,,,,,,,,,,,,,,,,,, \n K,,P,123 ST,,LAKEWOOD,CO,80228-5332,,,,,,,,,,,,,,,,,,,,';
我需要做两件事。
- 确保 address1、city、st 和 zip 不为空。
- 确保 zip 仅包含 5 个数字。
在 regext101.com 上测试了一些示例,但没有任何运气。甚至没有接近需要的东西。任何帮助,将不胜感激。谢谢!
【问题讨论】:
-
我不知道你的观点是什么意思。无论哪种方式,您具体尝试了什么?
-
如果
^(?:[^,]*,){3}([ ]*[^ ,][^,]*),[^,]*,([ ]*[^ ,][^,]*),([ ]*[^ ,][^,]*),(\d{5}),匹配,则通过您的测试。 -
谢谢你!像魅力一样工作。
标签: javascript regex csv