簡體   English   中英

創建一個正則表達式以刪除除換行符以外的連續空白

[英]Creating a Regex to remove consecutive whitespaces except for newlines

我想使用正則表達式執行以下操作:

  • 除換行符外的所有空白字符都必須轉換為空格(即\\f\\r\\t\\v將轉換為空格)
  • 一個字符串不能包含兩個或多個連續的空格,除了換行符。
    • 換行符最多只能連續出現兩次(即\\n可以, \\n\\n也可以,但是\\n\\n\\n不允許,應該用\\n\\n代替)。
  • 如果空格在換行符之前或之后,則應刪除該空格。

一些例子:

space-space => space
space-space-space => space
space-tab => space
space-tab-space => space
newline-newline => newline-newline
space-newline => newline
space-newline-newline => newline-newline
newline-space => newline
newline-space-newline => newline-newline

到目前為止,我能想到的唯一正則表達式就是這個,它刪除了所有連續的空格:

Regex.Replace(input, @"(\s)\s+", "$1");

要匹配除換行符以外的任何空格,可以使用[^\\S\\n]否定字符類。 或者, [\\s-[\\n]] ,但是我更喜歡第一個,因為它可以移植到其他正則表達式引擎中。

現在,您可以使用一個正則表達式,它將匹配可選的換行符,除了換行符外,還可以在1+空格的左邊和右邊匹配可選換行符。 然后,您可以檢查是否有任何換行符被匹配,如果是,則省略匹配的空格,否則,用空格替換匹配項。 然后,您將需要用兩個換行符替換3個或更多換行符的任何塊。

var result = Regex.Replace(input, @"(\n?)[^\S\n]+(\n?)", m =>
    !string.IsNullOrEmpty(m.Groups[1].Value) || !string.IsNullOrEmpty(m.Groups[2].Value) // If any \n matched
        ? $"{m.Groups[1].Value}{m.Groups[2].Value}" // Concat Group 1 and 2 values
        : " ");  // Else, replace the 1+ whitespaces matched with a space
var final_result = Regex.Replace(result, @"\n{3,}", "\n\n"); // Replace 3+ \ns with two \ns

細節

  • (\\n?) -捕獲組1:可選的換行符
  • [^\\S\\n]+ -除換行符外的1+個空格
  • (\\n?) -捕獲第2組:可選的換行符
  • \\n{3,} -3個或更多換行符。

一個簡單的多步驟解決方案如下:

除換行符外,所有空白字符都必須轉換為空格(即\\ f,\\ r,\\ t,\\ v將轉換為空格)

output = Regex.Replace(input, "[\\f\\r\\t\\v ]+", " ");

上面的組中包含一個空格。

如果空格在換行符之前或之后,則應刪除該空格。

output = Regex.Replace(output, " \n", "\n");
output = Regex.Replace(output, "\n ", "\n"); 

可以將上述兩個更改為使用String.Replace樣式:

output = output.Replace(" \n", "\n");
output = output.Replace("\n ", "\n");

甚至:

output = output.Replace(" \n", "\n").Replace("\n ", "\n");

一個字符串不能包含兩個或多個連續的空格,除了換行符。 換行符最多只能連續出現兩次(即\\ n可以,\\ n \\ n也可以,但是\\ n \\ n \\ n不允許,應該用\\ n \\ n代替)。

output = Regex.Replace(output, "\n\n\n+", "\n\n");

作為旁白。 如果系統對換行符使用\\r\\n ,那么抑制\\r字符可能會導致不良結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM