我是否正确认为
Regex不能用于检测缺失的括号(因为没有办法计算对)?使用
JavaScript我有大约一千个被截断的字符串,需要手工编辑.我希望能够将这个列表缩小到使用代码需要注意的列表.字符串可以被认为是:
>(这很好,不需要注意)
>这也是[罚款]
>这很糟糕(需要编辑
>这[也是(也)不好
>这是坏事
>此字符串没有任何类型的括号,但也必须考虑
如果这是不可能的,那么我只需编写一个函数来寻找支架对.谢谢
解决方法
- function isFine(str) {
- return /[(){}\[\]]/.test( str ) &&
- ( str.match( /\(/g ) || '' ).length == ( str.match( /\)/g ) || '' ).length &&
- ( str.match( /\[/g ) || '' ).length == ( str.match( /]/g ) || '' ).length &&
- ( str.match( /{/g ) || '' ).length == ( str.match( /}/g ) || '' ).length;
- }
测试
- isFine('(this is fine and does not need attention)'); // true
- isFine('This is also [fine]'); // true
- isFine('This is bad( and needs to be edited'); // false
- isFine('This [is (also) bad'); // false
- isFine('as is this} bad'); // false
- isFine('this string has no brackets but must also be considered'); // false
但请注意,这不会检查括号顺序,即a)b(c将被视为罚款.
对于记录,这是一个检查缺少括号并检查每种类型是否正确平衡的函数.它不允许a)b(c,但它确实允许(a [bc] d],因为每种类型都是单独检查的.
- function checkBrackets( str ) {
- var lb,rb,li,ri,i = 0,brkts = [ '(',')','{','}','[',']' ];
- while ( lb = brkts[ i++ ],rb = brkts[ i++ ] ) {
- li = ri = 0;
- while ( li = str.indexOf( lb,li ) + 1 ) {
- if ( ( ri = str.indexOf( rb,ri ) + 1 ) < li ) {
- return false;
- }
- }
- if ( str.indexOf( rb,ri ) + 1 ) {
- return false;
- }
- }
- return true;
- }
最后,进一步到Christophe的帖子,这里似乎是检查缺失括号并检查所有都是正确平衡和嵌套的最佳解决方案:
- function checkBrackets( str ) {
- var s;
- str = str.replace( /[^{}[\]()]/g,'' );
- while ( s != str ) {
- s = str;
- str = str.replace( /{}|\[]|\(\)/g,'' )
- }
- return !str;
- };
- checkBrackets( 'ab)cd(efg' ); // false
- checkBrackets( '((a)[{{b}}]c)' ); // true
- checkBrackets( 'ab[cd]efg' ); // true
- checkBrackets( 'a(b[c)d]e' ); // false