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

标签 javascript regex string

我正在使用 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/

相关文章:

相当于 php 的 urldecode() 的 Javascript

javascript - 具有初始速度的动画

javascript - 是对象还是数组?哪一个?

java - 如何有效地从另一个字符串中删除一个字符串的所有实例?

C# OLEDB 保护查询中的撇号

输出语句末尾的 Javascript 对象未定义关键字

java - 从 url 中提取特定字段

java - 重复替换调用导致 java.lang.OutOfMemoryError

html - 使用正则表达式在 HTML 中进行搜索? [ swift 1.2]

c++ - 在 C++ 中从用户输入中剥离/删除符号