RegEx replace char period char

Started by
4 comments, last by NightCreature83 11 years, 7 months ago
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.
Advertisement
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
Works for me

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)).
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Thanks guys I appreciate your feedback.
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.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement