繁体   English   中英

使用正则表达式字符串替换正则表达式字符类

[英]String replace regex character classes using regex

此字符串包含需要删除的正则表达式字符类。 以及将多个空间减少为单个空间。
我可以链接replace()但想问一问是否可以建议一个正则表达式代码一次完成整个工作。 如何做呢? 谢谢

“ \\ n \\ t \\ t \\ t \\ n \\ n \\ t \\ n \\ t \\ t \\ t食物和饮料\\ n \\ t \\ n”

这是必需的:

“食物和饮料”

var newStr = oldStr.replace(/[\t\n ]+/g, '');  //<-- failed to do the job

我建议使用这种模式(假设您要在主字符串中保留\\n\\t ):

/^[\t\n ]+|[\t\n ]+$/g

如果您不想保留它们,可以使用以下方法:

/^[\t\n ]+|[\t\n]*|[\t\n ]+$/g

您要删除所有前导和尾随空格(空格,制表符,换行符),但将空格保留在内部字符串中。 您可以使用空格字符类\\s速记,并匹配开始字符串的结尾。

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood and drinks \n \t\n";

// ^\s+ => match one or more whitespace characters at the start of the string
// \s+$ => match one or more whitespace characters at the end of the string
// | => match either of these subpatterns
// /g => global i.e every match (at the start *and* at the end)

var newStr = oldStr.replace(/^\s+|\s$/g/, '');

如果你也想减少内部空间,以一个单一的空间,我建议使用两个正则表达式和链接它们:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood   and      drinks \n \t\n";
var newStr = oldStr.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');

在第一个.replace()之后,所有前导和尾随空格都将被删除,仅保留内部空间。 用一个空格替换一个或多个空格/制表符/换行符的运行。

可以采取的另一种方法是将所有空白空间减少到一个空格,然后修剪剩余的前导和尾随空格:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood   and      drinks \n \t\n";

var newStr = oldStr.replace(/\s+/g, ' ').trim();
// or reversed
var newStr = oldStr.trim().replace(/\s+/g, ' ');

.trim()不ES5.1之前存在(ECMA-262),但填充工具基本上是.replace(/^\\s+|\\s+$/g, '')添加了几个其他的字符)反正。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM