我有一个字符串如下
const example = ' ( some string ()() here ) ';
如果我用
修剪字符串example.trim()
它将给我输出:( some string ()() here )
但是我想要输出some string ()() here
。如何实现?
const example = ' ( some string ()() here ) ';
console.log(example.trim());
答案 0 :(得分:6)
您可以将正则表达式用于开头和结尾的空格/括号:
<C-A/X>
/^\s+\(\s+(.*)\s+\)\s+$/g
如果字符串是可选的前导和/或结尾,则需要创建一些可选的非捕获组
function grabText(str) {
return str.replace(/^\s+\(\s+(.*)\s+\)\s+$/g,"$1");
}
var strings = [
' ( some (string) here ) ',
' ( some string ()() here ) '];
strings.forEach(function(str) {
console.log('>'+str+'<')
console.log('>'+grabText(str)+'<')
console.log('-------')
})
/^(?:\s+\(\s+?)?(.*?)(?:\s+\)\s+?)?$/g
/^ - from start
(?:\s+\(\s+?)? - 0 or more non-capturing occurrences of ' ( '
(.*?) - this is the text we want
(?:\s+\)\s+?)? - 0 or more non-capturing occurrences of ' ) '
$/ - till end
g - global flag is not really used here
答案 1 :(得分:4)
您可以使用正则表达式获取匹配的字符串,下面的正则表达式匹配第一个字符,后跟字符或空格,并以字母数字字符结尾
const example = ' ( some (string) ()()here ) ';
console.log(example.match(/(\w[\w\s.(.*)]+)\w/g));
答案 2 :(得分:1)
如果您要在修剪后仅移除外部支架,则可以使用
var input = ' ( some string ()() here ) '.trim();
if( input.charAt(0) == '(' && input.charAt(input.length-1) == ')') {
var result = input.slice(1, -1).trim()
console.log(result)
}
最后一个修剪是可选的,它可以删除(
和s
之间的空格,e
和)
答案 3 :(得分:0)
class ClassWeights(object):
"""
Draw random variates for cases when parameter is a dict.
Should be personalized as needed.
"""
def __init__(self,y, *args, **kwargs):
self.class_weights = compute_class_weight("balanced", np.unique(y), y)
self._make_dists()
def _make_dists(self):
self.dist0 = gamma(self.class_weights[0])
self.dist1 = gamma(self.class_weights[1])
def rvs(self, *args, **kwargs):
"""override method for drawing random variates"""
ret_val = { 0: self.dist0.rvs(*args, **kwargs),
1: self.dist1.rvs(*args, **kwargs)}
return ret_val
答案 4 :(得分:0)
您可以使用递归方法并指定希望修剪字符串的次数。这也可以用于圆括号以外的其他内容,例如方括号:
const example = ' ( some string ()() here ) ';
const exampleTwo = ' [ This, is [some] text ] ';
function trim_factor(str, times) {
if(times == 0) {
return str;
}
str = str.trim();
return str.charAt(0) + trim_factor(str.substr(1, str.length-2), times-1) + str.charAt(str.length-1);
}
console.log(trim_factor(example, 2));
console.log(trim_factor(exampleTwo, 2));