用正则表达式包装的单词

Jus*_*der 15 c# regex word-wrap

编辑清晰度 - 我知道有多种方法可以在多个步骤中执行此操作,或使用LINQ或vanilla C#字符串操作.我使用单个正则表达式调用的原因是因为我想练习复杂的正则表达式模式. - 结束编辑

我正在尝试编写一个将执行自动换行的正则表达式.它非常接近所需的输出,但我无法让它工作.

Regex.Replace(text, @"(?<=^|\G)(.{1,20}(\s|$))", "$1\r\n", RegexOptions.Multiline)
Run Code Online (Sandbox Code Playgroud)

这是正确包装太长的行的单词,但它已经有一个换行符.

输入

"This string is really long. There are a lot of words in it.\r\nHere's another line in the string that's also very long."
Run Code Online (Sandbox Code Playgroud)

预期产出

"This string is \r\nreally long. There \r\nare a lot of words \r\nin it.\r\nHere's another line \r\nin the string that's \r\nalso very long."
Run Code Online (Sandbox Code Playgroud)

实际产出

"This string is \r\nreally long. There \r\nare a lot of words \r\nin it.\r\n\r\nHere's another line \r\nin the string that's \r\nalso very long.\r\n"
Run Code Online (Sandbox Code Playgroud)

注意输入已经有换行符的句子和最后放置的额外"\ r \n"之间的双"\ r \n".

也许有条件地应用不同的替换模式?IE如果匹配以"\ r \n"结尾,请使用替换模式"$ 1",否则,使用替换模式"$ 1\r \n".

这是一个类似问题的链接,用于包装一个没有空格的字符串,我用它作为起点. 正则表达式,用于查找完整文本和插入空间

小智 9

这是在Perl中快速测试的.

编辑 - 此正则表达式代码模拟MS-Windows Notepad.exe中使用的自动换行(好或坏)

 # MS-Windows  "Notepad.exe Word Wrap" simulation
 # ( N = 16 )
 # ============================
 # Find:     @"(?:((?>.{1,16}(?:(?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|.{1,16})(?:\r?\n)?|(?:\r?\n|$))"
 # Replace:  @"$1\r\n"
 # Flags:    Global     

 # Note - Through trial and error discovery, it apparears Notepad accepts an extra whitespace
 # (possibly in the N+1 position) to help alignment. This matters not because thier viewport hides it.
 # There is no trimming of any whitespace, so the wrapped buffer could be reconstituted by inserting/detecting a
 # wrap point code which is different than a linebreak.
 # This regex works on un-wrapped source, but could probably be adjusted to produce/work on wrapped buffer text.
 # To reconstitute the source all that is needed is to remove the wrap code which is probably just an extra "\r".

 (?:
      # -- Words/Characters 
      (                       # (1 start)
           (?>                     # Atomic Group - Match words with valid breaks
                .{1,16}                 #  1-N characters
                                        #  Followed by one of 4 prioritized, non-linebreak whitespace
                (?:                     #  break types:
                     (?<= [^\S\r\n] )        # 1. - Behind a non-linebreak whitespace
                     [^\S\r\n]?              #      ( optionally accept an extra non-linebreak whitespace )
                  |  (?= \r? \n )            # 2. - Ahead a linebreak
                  |  $                       # 3. - EOS
                  |  [^\S\r\n]               # 4. - Accept an extra non-linebreak whitespace
                )
           )                       # End atomic group
        |  
           .{1,16}                 # No valid word breaks, just break on the N'th character
      )                       # (1 end)
      (?: \r? \n )?           # Optional linebreak after Words/Characters
   |  
      # -- Or, Linebreak
      (?: \r? \n | $ )        # Stand alone linebreak or at EOS
 )
Run Code Online (Sandbox Code Playgroud)

测试用例 包装宽度N为16.输出与记事本和各种宽度相匹配.

 $/ = undef;

 $string1 = <DATA>;

 $string1 =~ s/(?:((?>.{1,16}(?:(?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|.{1,16})(?:\r?\n)?|(?:\r?\n|$))/$1\r\n/g;

 print $string1;

 __DATA__
 hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
 bbbbbbbbbbbbbbbbEDIT FOR CLARITY - I                    know there are  ways to do this in   multiple steps, or using LINQ or vanilla C#
 string manipulation. 

 The reason I am using a single regex call, is because I wanted practice. with complex
 regex patterns. - END EDIT
 pppppppppppppppppppUf
Run Code Online (Sandbox Code Playgroud)

输出>>

 hhhhhhhhhhhhhhhh
 hhhhhhhhhhhhhhh
 bbbbbbbbbbbbbbbb
 EDIT FOR CLARITY 
 - I              
       know there 
 are  ways to do 
 this in   
 multiple steps, 
 or using LINQ or 
 vanilla C#
 string 
 manipulation. 

 The reason I am 
 using a single 
 regex call, is 
 because I wanted 
 practice. with 
 complex
 regex patterns. 
 - END EDIT
 pppppppppppppppp
 pppUf
Run Code Online (Sandbox Code Playgroud)


L.B*_*L.B 5

我会写一个这样的扩展方法。

var input = "This string is really long. There are a lot of words in it.\r\nHere's another line in the string that's also very long.";

var lines = input.SplitByLength(20).ToList();
Run Code Online (Sandbox Code Playgroud)
public static partial class MyExtensions
{
    public static  IEnumerable<string> SplitByLength(this string input, int maxLen)
    {
        return Regex.Split(input, @"(.{1," + maxLen + @"})(?:\s|$)")
                    .Where(x => x.Length > 0)
                    .Select(x => x.Trim());
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

This string is
really long. There
are a lot of words
in it.
Here's another line
in the string that's
also very long.
Run Code Online (Sandbox Code Playgroud)

  • 否决票没有意义。该解决方案显然比 OP 的实际方法要好。 (4认同)