繁体   English   中英

正则表达式用逗号分隔验证字符串

[英]Regex validate string with comma-separated

我正在使用 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}$/);

尝试下面的正则表达式只接受字符串。

 // first test let text = 'AB1234567'; // output: 'AB1234567' let regex = /[a-zA-Z0-9]+/g let hasText = text.match(regex); // is good. console.log(hasText); // second test text = 'AB1234567, '; // output: 'AB1234567, ' hasText = text.match(regex); // is good, but I dont need this. console.log(hasText); // third test text = 'AB1234567, AB1234568'; // output: 'AB1234567, AB1234568' hasText = text.match(regex); // is good, I need this. console.log(hasText); // fourth test text = 'AB1234567, AB1234568, '; // output: 'AB1234567, AB1234568, ' hasText = text.match(regex); console.log(hasText);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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