0

I am using the following code to find any instances of "\n" newline that doesn't have a space on both sides and add a space on both sides.

Scenarios

  1. There is a space on both sides of /n. = Do Nothing
  2. There is a space either before or after the /n = Add a space on both sides.
  3. There are no spaces on either side = Add a space on both sides.

But why do you need this?

I need to space seperate words in a paragraph without affecting the paragraph structure. If I split by /s then the structure is gone, so in order to maintain it I want to put a space on either side of the /n new line.

This looks ok, whats the problem?

This works for new version of Chrome, but doesn't work for old version and doesn't work for Safari and needs to be support across browsers

Question:

How can I maintain this logic without using non Safari supported Regex using Dart.

Code Example

var regex = RegExp("\n(?! )|(?<! )\n");

if (text.contains(regex)) {
  String newString = text.replaceAll(regex, " \n ");
  updatedString = newString;
}
Yonkee
  • 1,551
  • 3
  • 26
  • 51

1 Answers1

0

You can use

var regex = RegExp(" ?\n ?");
updatedString = text.replaceAll(regex, " \n ");

See the regex demo

The " ?\n ?" pattern matches an optional space, then a newline, and then an optional space, and then the match is replaced with a space+newline+space yielding the expected result: if there is are spaces on left and right, they are kept, else, a space is added.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476