【效率工具】正则表达式匹配可视化工具

mac2024-03-05  30

正则表达式匹配可视化工具

通过对正则表达式进行实时的测试,标注出那一部分匹配对应的另外一部分。最重要的特征就是实时性。

工具说明

实现参考

<template> <div> <div> <label>Regex:</label> <br/> <textarea v-model="regex" style="width: 300px"></textarea> </div> <div> <label>Tests:</label> <br/> <textarea v-model="tests" style="width: 500px"></textarea> </div> <div :style="{color: matchColor}">{{matchState}}</div> <div v-if="matches"> <div v-for="(group,idx) in matchGroups"> <span>group[{{idx}}] = {{group}}</span> </div> </div> </div> </template> <script> // RegExp = regular expression // let reg = new RegExp(...) // reg.test(...) // test if the string matches the expression // // // Usage: // exec(s) -> reg exp updates its lastIndex when 'g' is set // and exec(s) starts to search at lastIndex, if no 'g' specified,it will be a dead loop // you can check lastIndex to ensure the whole string is matched when setting 'g'. // // test(s) -> returns true or false // var myRe = /ab*/g; // var str = 'abbcdefabh'; // var myArray; // while ((myArray = myRe.exec(str)) !== null) { // var msg = 'Found ' + myArray[0] + '. '; // msg += 'Next match starts at ' + myRe.lastIndex; // console.log(msg); // } // Example: // a=/(a)(b)*(c)/g.exec("abbbc") // [0]=abc [1]=a [2]=b [3]=c // Note that group is literal, * outside a group catch is not catched // a=/(a)(b*)(c)/g.exec("abbbc") // [0]=abc [1]=a [2]=bbb [3]=c // // assertation: // x(?=y) assert suffix y // x(?!y) assert no suffix y module.exports = { name: "RegexMatcherLivePreview", data(){ return { regex:"", tests:"", result:"", matches:false, matchGroups:[] // tests:[] } }, methods:{ updateMatch(){ this.compiledRegex.lastIndex = 0 this.matches = false let arr = this.compiledRegex.exec(this.tests) if(arr===null || this.compiledRegex.lastIndex!=this.tests.length){ this.matchGroups = [] }else{ this.matches = true this.matchGroups = arr } } }, computed:{ compiledRegex(){ return new RegExp(this.regex, 'g') }, matchState(){ return this.matches ? "Match": "Not Match" }, matchColor(){ return this.matches? "green" : "red" } }, watch:{ 'regex':function(val){ this.updateMatch() }, 'tests':function (val) { this.updateMatch() } } } </script> <style scoped> </style>
最新回复(0)