Reputation: 45
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
Reputation: 2401
The correct regex: (?: )?\r\n
Some points to consider:
(?:(?: )?\r\n)+
[ ]
is the same as [ ]
, which means "match either a space or a space or a space...".Upvotes: 3