Note that there are some explanatory texts on larger screens.

plurals
  1. POWord Wrapping with Regular Expressions
    primarykey
    data
    text
    <p>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</p> <p>I am trying to write a single regular expression that will perform word wrapping. It's extremely close to the desired output, but I can't quite get it to work.</p> <pre><code>Regex.Replace(text, @"(?&lt;=^|\G)(.{1,20}(\s|$))", "$1\r\n", RegexOptions.Multiline) </code></pre> <p>This is correctly wrapping words for lines that are too long, but it's adding a line break when there already is one.</p> <p>Input</p> <pre><code>"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." </code></pre> <p>Expected Output</p> <pre><code>"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." </code></pre> <p>Actual Output</p> <pre><code>"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" </code></pre> <p>Note the double "\r\n" between sentences where the input already had a line break and the extra "\r\n" that was put at the end.</p> <p>Perhaps there's a way to conditionally apply different replacement patterns? I.E. If the match ends in "\r\n", use replace pattern "$1", otherwise, use replace pattern "$1\r\n".</p> <p>Here's a link to a similar question for wrapping a string with no white space that I used as a starting point. <a href="https://stackoverflow.com/questions/4749265/regular-expression-to-find-unbroken-text-and-insert-space">Regular expression to find unbroken text and insert space</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload