我需要删除特殊字符之间的空格。我有一个字符串:
app.directive('imgDimensionsBindDirective', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
element.bind('load', function() {
ngModel.$setViewValue(angular.toJson({width: element[0].clientWidth,height: element[0].clientHeight}));
});
}
}
});
我想要一个这样的字符串:
abc = "test = > @ Stack overflow"
以便只删除之间,之前或之后的空格。无法为此创建正确的正则表达式或方法。任何提示或想法?
答案 0 :(得分:4)
您可以使用以下代码:
abc = "test = > @ Stack overflow"
puts abc.gsub(/\s*([^\s\p{L}\p{N}])\s*/, "\\1")
请参阅IDEONE demo,结果:test=>@Stack overflow
。
捕获组是恢复捕获的“特殊”角色所必需的。
[^\s\p{L}\p{N}]
代表非空格,非字母和非数字字符。