Glooow8
Glooow8

Reputation: 45

Trouble with exceptions using regex

I have this line of code:

textBox1.Text = Regex.Replace(textBox1.Text, "(?:\r\n)+", "  \r\n");

which basically adds a double spacebar to the line before a line break:

Input:

a

b
c
d

e

Output:

a  //<--- Double spacebar after the 'a' character
b  //<--- Double spacebar after the 'b' character
c  //<--- Double spacebar after the 'c' character
d  //<--- Double spacebar after the 'd' character
e

for some formatting purposes on pages like this one or reddit, which need either a double break line or a double spacebar in the previous line and a single line break afterwards to make a new line in their formatting

Anyway, It's working, but the problem is that if you already have a double spacebar after the line, it just keeps adding and results in a line with too many spacebars, which are unnecesary because you only need 2 for this to work

So I've tried doing an exception with [^ ], which should not consider the rule if it already has a double spacebar before, like this:

(?:[^  ]\r\n)+

But it doesn't work?

Input:

a

b
c  //<---- Double spacebar before the line break to check if it ignores it
d

e

Output:

//<--- double spacebar here??

//<--- blank line, nothing there

//<--- double spacebar here??

c //<--- double spacebar here??

//<--- double spacebar here??

e

Why? What's wrong? Thank you very much

Upvotes: 2

Views: 46

Answers (1)

NH.
NH.

Reputation: 2401

The correct regex: (?: )?\r\n

Some points to consider:

  1. If you really do want to "collapse" multiple newlines into one as your original regex hints (with the + sign), then wrap my entire regex in a non-capturing group with a plus: (?:(?: )?\r\n)+
  2. Yes, my regex will replace a double-space-line-break with the exact same thing, but that is OK and better than adding extra spaces, as you mentioned.
  3. Adding the same character to a character class (using [brackets]) multiple times has no meaning. so [ ] is the same as [ ], which means "match either a space or a space or a space...".

Upvotes: 3

Related Questions