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,781
  • 3
  • 31
  • 56
  • Do you want to keep your regex functionality as is? `\n(?! )|(?<! )\n` regex will match a newline that is either not followed with a space or a newline that has no space before, and add spaces on *both* ends, this is a wrong pattern, IMHO. – Wiktor Stribiżew Oct 15 '20 at 20:54
  • @WiktorStribiżew Im open to any suggestions that match the scenarios that I mentioned. the key thing is how to do without look aheads that Safari doesn't support. I appreciate your help – Yonkee Oct 15 '20 at 21:00
  • I am not sure, what about `RegExp(" ?\n ?")` and keep on using `text.replaceAll(regex, " \n ")`? – Wiktor Stribiżew Oct 15 '20 at 21:12
  • @WiktorStribiżew Hmmm.. How would that work? what does that regex do? – Yonkee Oct 15 '20 at 21:17
  • See [demo & explanation](https://regex101.com/r/QqvLCD/1). Adds single spaces around newline if missing keeping them if they are both there. – Wiktor Stribiżew Oct 15 '20 at 21:18
  • @WiktorStribiżew That looks like it might work, let me update my code and test it. – Yonkee Oct 15 '20 at 21:23
  • What does a browser has to do with what seems to be pure dart code? – Alex.F Oct 15 '20 at 21:41
  • @WiktorStribiżew That works great on Safari as well and older version of Chrome and FF. Thanks. Please add it as an answer and I will accept it. – Yonkee Oct 15 '20 at 21:53
  • @Alex.F Flutter Web uses Dart. – Yonkee Oct 15 '20 at 21:53

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
  • 607,720
  • 39
  • 448
  • 563