Reputation: 1373
I have a string in C# which can have multiple \n
characters. For e.g. :
string tp = "Hello\nWorld \n\n\n !!";
If there is a single occurrence of \n
I want to replace it with something, but if more than one \n
appear together in the same place I want to leave them alone. So for the tp
string above I want to replace the \n
between Hello
and World
, because there is only one at that place, and leave the the three \n
nearer the end of the string alone, because they appear in a group.
If I try to use the Replace()
method in C# it replaces all of them. How can I resolve this issue?
Upvotes: 2
Views: 765
Reputation: 316
Use regular expressions and combine negative lookbehind and lookahead:
var test = "foo\nbar...foo\n\nbar\n\n\nfoo\r\nbar";
var replaced = System.Text.RegularExpressions.Regex.Replace(test, "(?<!\n)\n(?!\n)", "_");
// only first and last \n have been replaced
While searching through the input the regex "stops" at any "\n"
it finds and verifies if no "\n"
is one character behind the current position or ahead.
Thus only single "\n"
will be replaced.
Upvotes: 0
Reputation: 74605
A solution using loops:
char[] c = "\t"+ tp + "\t".ToCharArray();
for(int i = 1; i < c.Length - 1; i++)
if(c[i] == '\n' && c[i-1] != '\n' && c[i+1] != '\n')
c[i] = 'x';
tp = new string(c, 1, c.Length-2);
Upvotes: 0
Reputation: 186668
You can try using regular expressions: let's change \n
into "*"
whenever \n
is single:
using System.Text.RegularExpressions;
...
string tp = "Hello\nWorld \n\n\n !!";
// "Hello*World \n\n\n !!";
string result = Regex.Replace(tp, "\n+", match =>
match.Value.Length > 1
? match.Value // multiple (>1) \n in row: leave intact
: "*"); // single ocurrence: change into "*"
Upvotes: 3