缺少正则表达式的括号 [英] Missing parentheses with Regex
问题描述
我是否认为正则表达式不能用于检测缺失的括号(因为无法计算对)?使用JavaScript我有大约一千个被截断的字符串,需要手工编辑。我希望能够将这个列表缩小到使用代码需要注意的列表。字符串可以被认为是:
Am I correct in thinking that Regex can't be used to detect missing parentheses (because there is no way of counting pairs)? Using JavaScript I've about a thousand strings which have been truncated and need to be edited by hand. I was hoping to be able to narrow this list down to the ones that need attention using code. The strings can be thought of in the form of:
- (这很好,不需要注意)
- 这也是[罚款]
- 这很糟糕(需要进行编辑)
- 这[[也]错了
- 这是坏的
- 此字符串没有任何类型的括号,但也必须考虑
- (this is fine and does not need attention)
- This is also [fine]
- This is bad( and needs to be edited
- This [is (also) bad
- as is this} bad
- this string has no brackets of any kind but must also be considered
如果这不可能,那么我只需编写一个函数来寻找支架对。谢谢
If this is not possible then I'll just have to write a function to look for bracket pairs. Thank you
推荐答案
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
将被视为罚款。
Note though, that this doesn't check bracket order, i.e. a)b(c
would be deemed fine.
对于记录,这是一个检查缺少括号并检查每种类型是否正确平衡的函数。它不允许 a )b(c
,但它确实允许(a [bc] d]
,因为每种类型都是单独检查的。
For the record, here is a function that checks for missing brackets and checks that each type is correctly balanced. It doesn't allow a)b(c
, but it does allow (a[bc)d]
as each type is checked individually.
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的帖子,这里似乎是检查的最佳解决方案缺少括号并检查所有是否正确平衡和嵌套:
Finally, further to Christophe's post, here is what seems the best solution to checking for missing brackets and checking that all are correctly balanced and nested:
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
这篇关于缺少正则表达式的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!