编辑清晰度 - 我知道有多种方法可以在多个步骤中执行此操作,或使用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 …
Run Code Online (Sandbox Code Playgroud)