Jump to content
  • Advertisement
Sign in to follow this  
Headkaze

RegEx replace char period char

This topic is 2229 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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. Edited by Headkaze

Share this post


Link to post
Share on other sites
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;
}
Edited by Headkaze

Share this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!