如何匹配小写字母和一些标点字符?
如何匹配小写字母和一些标点字符?
期望行为
我有一个输入字段(表单的文本区域),我想允许以下字符:
- 小写字母
- 单个空格
- 单个逗号
- 单引号
- 单破折号
基本上,只允许人们在上述限制范围内自由输入文本。
实际行为
我创建的模式根本没有捕获定义的标点符号,也未按预期执行:
- 逗号没有匹配
- 单引号匹配,但多个单引号也匹配
- 破折号没有匹配
我已经尝试过的
我基于以下资源构建:
https://stackoverflow.com/a/15472787
https://www.regextester.com/104025
https://stackoverflow.com/a/7233549
以得到:
模式
var pattern = /^[a-z]+( [a-z,'-]+)*$/gm;
测试
Valid: hello what how are you the person's thing how, are you dash - between words how-are-you Not Valid: how are you? hi5 8ask yyyy. ! dff NoSpecialcharacters# 54445566 how are you how-are------you the person''s thing how,, are you
测试代码
// define an array of tests var array_of_tests = ["hello", "what", "how are you", "how are you?", "hi5", "8ask", "yyyy.", "! dff", "NoSpecialcharacters#", "54445566", "how are you", "how-are-you", "how-are------you", "the person's thing", "the person''s thing", "how, are you", "how,, are you"]; // define the pattern var pattern = /^[a-z]+( [a-z,'-]+)*$/gm; // iterate over the array of tests for (let t = 0; t < array_of_tests.length; t++) { // create reference to test var test = array_of_tests[t]; // see if test matches pattern var result = test.match(pattern); // log results if (result !== null) { console.log("MATCHED"); console.log(test); console.log(result); } else { console.log("NOT MATCHED"); console.log(test); console.log(result); } console.log("==============="); }
问题
除了让期望的行为正常工作外,我想知道:
是否有一种简单的方法来添加和删除正则表达式中所需的标点符号?
admin 更改状态以发布 2023年5月22日