簡體   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