【发布时间】:2020-10-17 08:18:50
【问题描述】:
要求:
- 字符串中不能有大写字母。
- 字符串不能包含任何字符'^$.?*+()'
- 如果字符串中存在“[”,则它后面必须跟零个或多个字符,而不是“[”和“]”,后者后面必须跟“]”。例如,[test] 有效,而 [test not valid, test] 和 [[test]] 无效。 [test][test] 有效。
- '|' | 后面有的话可以用喜欢 |||无效但 |测试有效字|无效
function charPos(str, char) {
return str
.split("")
.map(function (c, i) { if (c == char) return i; })
.filter(function (v) { return v >= 0; });
}
function testString(urlPattern)
{
let regex = /[ $^*()+\[\]\\|.\/?]/g;
if(regex.test(urlPattern)){
let secondRegex = true;
let thirdRegex = true;
let regexData = /[ $^*()+\\\\.\/?]/g;
let regexDataNew = /[ $^*()+\\\.\/?]/g;
if(urlPattern.indexOf("[") < urlPattern.indexOf("]") && !regexData.test(urlPattern)){
secondRegex = false;
}
if(urlPattern.indexOf("[") == -1 && urlPattern.indexOf("]") == -1){
secondRegex = false;
}
if(urlPattern.indexOf("[[") != -1 || urlPattern.indexOf("]]") != -1){
secondRegex = true;
}
let pos = charPos(urlPattern,'|');
let largest = pos.sort((a,b)=>a-b)[pos.length - 1];
if(largest+1 < urlPattern.length && !regexDataNew.test(urlPattern)){
thirdRegex = false;
}
if(urlPattern.indexOf("|") == -1 ){
thirdRegex = false;
}
if(secondRegex || thirdRegex){
return 'Not Valid';
}
else {
return 'Valid';
}
}
else {
return 'Valid1';
}
}
// test case
testString('testttthhh@@|sss'); working
testString('testttthhh@@|'); working
testString('testttthhh@@|[]') working but need to show invalid.
如果有人有解决方案或遇到相同类型的问题,请帮我解决。
谢谢
【问题讨论】:
-
结帐Regex101。它包括字符串测试和针对多种风格的超级有用的快速参考指南,包括 ECMAScript (JavaScript)。
-
我已经编辑了您的问题,试图使要求更加清晰。但是,您会看到第三点和第四点仍然不清楚。那是因为我不完全理解那里允许和不允许的内容。您需要编辑您的问题以使要点正确且明确。您还需要更改标题,我不想说,这很糟糕。 :-)
标签: javascript regex reactjs