实现原理
最终效果
完整代码
<template> <div style="padding: 30px"> <p>校验规则 :</p> <ol> <li>括号不能嵌套</li> <li>括号必须成对出现</li> </ol> <el-input clearable placeholder="请输入例句!" v-model="exampleString" style="width: 400px" ></el-input> <p> 校验结果: <span :style="{ color: errorMsg ? 'red' : 'green', }" > {{ errorMsg || "校验通过" }}</span > </p> </div> </template> <script> export default { data() { return { exampleString: "", errorMsg: "", }; }, watch: { exampleString(val) { this.errorMsg = this.check(val); }, }, methods: { check(str) { let errorMsg = ""; let leftBracketsList = ["(", "(", "[", "{"]; let rightBracketsList = [")", ")", "]", "}"]; let BracketsDic = { "(": ")", "(": ")", "[": "]", "{": "}", }; let leftBracket = null; let leftBracketIndex = null; let index = 1; for (let char of str) { // 是否左括号 if (leftBracketsList.includes(char)) { // 是否已有左括号 if (leftBracket) { errorMsg = `因括号不可嵌套,第${leftBracketIndex}个字符 ${leftBracket} 在匹配右括号前,不能出现第${index}个字符 ${char} `; break; } else { leftBracket = char; leftBracketIndex = index; } } else { // 是否右括号 if (rightBracketsList.includes(char)) { // 是否已有左括号 if (leftBracket) { // 是否匹配左括号 if (BracketsDic[leftBracket] === char) { leftBracket = null; leftBracketIndex = null; } else { errorMsg = `第${leftBracketIndex}个字符 ${leftBracket} 与第${index}个字符 ${char} 不匹配`; break; } } else { errorMsg = `第${index}个字符 ${char} 前缺少左括号`; break; } } } index++; } if (!errorMsg) { if (leftBracket) { errorMsg = `第${leftBracketIndex}个字符 ${leftBracket} 后缺少右括号`; } } return errorMsg; }, }, }; </script>