我正在使用 JavaScript,如果有更多字符串,我只需要接受字符串或以逗号分隔的字符串。
我的代码如下
const text = 'AB1234567';
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/);
我的代码测试如下
// first test
const text = 'AB1234567'; // output: 'AB1234567'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good.
// second test
const text = 'AB1234567, '; // output: 'AB1234567, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.
// third test
const text = 'AB1234567, AB1234568'; // output: 'AB1234567, AB1234568'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, I need this.
// fourth test
const text = 'AB1234567, AB1234568, '; // output: 'AB1234567, AB1234568, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.
我怎样才能只接受正确的值?
正确值是第一次测试和第三次测试
最佳答案
您的正则表达式将接受以逗号和空格结尾的字符串,这显然是您不想要的。因此,让我们让正则表达式强制字符串不会以这种方式结束:text.match(/^([A-Za-z]{2}[0-9]{7},\s)*[A-Za-z]{2}[0-9]{7}$/);
关于javascript - 正则表达式用逗号分隔验证字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59701510/