Sign in to follow this  
Headkaze

RegEx replace char period char

Recommended Posts

I need to process some text using RegEx to change any occurance of a [b]character, period then character[/b] to a [b]character, period, space then character[/b]. 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. Edited by Headkaze

Share this post


Link to post
Share on other sites
This is what I have so far but it doesn't seem to be ignoring the characters correctly

[code]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;
}[/code] Edited by Headkaze

Share this post


Link to post
Share on other sites
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.

[url="http://www.dotnetperls.com/newline"]http://www.dotnetperls.com/newline[/url] Edited by ShadowValence

Share this post


Link to post
Share on other sites
Works for me
[code]
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}"));
}
}
[/code]

([url="http://ideone.com/TB5Iu"]results[/url])

[edit]

To explain the magic, they're called capture groups. [url="http://adamprescott.net/2012/03/09/regular-expression-capture-groups-in-c/"]This page does a decent-ish job explaining capture groups[/url] (though he focuses on named capture groups (I used unnamed capture groups, hence why I referred to them by their number)). Edited by Cornstalks

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this