Gho*_*ool 7 javascript regex parentheses
我是否正确认为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;
}
Run Code Online (Sandbox Code Playgroud)
测试
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
Run Code Online (Sandbox Code Playgroud)
但请注意,这不会检查括号顺序,即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;
}
Run Code Online (Sandbox Code Playgroud)
最后,进一步到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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2917 次 |
| 最近记录: |