I need to process some text using RegEx to change any occurance of a character, period then character to a character, period, space then character. It also needs to ignore a period with a newline, period or space after it.
Eg. This is a test.This is a test => This is a test. This is a test
Also I need to have an option to have the space be a newline character instead.
I'm not sure if I can use RegEx.Replace because I need to include the characters around the period in the result.
RegEx replace char period char
This is what I have so far but it doesn't seem to be ignoring the characters correctly
public static string FixCharDotChar(string str, bool addNewLine)
{
Regex regex = new Regex(@".\.[^ \n\.]");
foreach (Match match in regex.Matches(str))
{
if (match.Length != 3)
continue;
string strMatch = match.Value;
strMatch = strMatch.Insert(2, (addNewLine ? Environment.NewLine : " "));
str = str.Replace(match.Value, strMatch);
}
return str;
}
You may want to try [source lang="csharp"]\r\n[/source] as your newline. Memory is a bit hazy, but it may help.
Alternatively you could use:
[source lang="csharp"] Environment.NewLine [/source] as you are in your string insertion logic.
http://www.dotnetperls.com/newline
Alternatively you could use:
[source lang="csharp"] Environment.NewLine [/source] as you are in your string insertion logic.
http://www.dotnetperls.com/newline
Works for me
(results)
[edit]
To explain the magic, they're called capture groups. This page does a decent-ish job explaining capture groups (though he focuses on named capture groups (I used unnamed capture groups, hence why I referred to them by their number)).
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string str = "Hello.world. This..is a test.\nso yeah...";
Console.WriteLine(new Regex(@"(.)\.([^\s\.])").Replace(str, "${1}. ${2}"));
}
}
(results)
[edit]
To explain the magic, they're called capture groups. This page does a decent-ish job explaining capture groups (though he focuses on named capture groups (I used unnamed capture groups, hence why I referred to them by their number)).
Using Environment.Newline is still adviced though in C# as new lines could be set to \n\r or \r or \n, the environment one will input the correct one in each circumstance.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement