Issue with "RegularExpressions.Regex.Replace"

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

I have another question about Regular Expression. If I use:

if (temp.Contains("Ending") == true)
{
temp =
System.Text.RegularExpressions.Regex.Replace(temp, "Ending",
"Beginning");
}

It seems that while "Ending" is replaced with "Beginning", it also
deletes the space after "Ending". For instance, "Period Ending July
31, 2007" is now "Period BeginningJuly 31, 2007" (Note: no space
betweem "Beginning" and "July" after Replace).

Any advice?
 
Curious,

Not sure what you're doing wrong in your code but here is mine and it
works as expected. I'm using VS.NET 2005.

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace RegEx
{
class Program
{
static void Main(string[] args)
{
string test = "Period Ending July 31, 2007";
string test2 = Regex.Replace(test, "Ending", "Beginning");
// Test2 is now "Period Beginning July 31, 2007"
}
}
}

Also not that your temp.Contains(...) is not necessary. If
Regex.Replace(...) find it, it will replace the string. No need to
check for it.

Jason Newell
Software Engineer
www.jasonnewell.net
 
Curious said:
I have another question about Regular Expression. If I use:

if (temp.Contains("Ending") == true)
{
temp =
System.Text.RegularExpressions.Regex.Replace(temp, "Ending",
"Beginning");
}

It seems that while "Ending" is replaced with "Beginning", it also
deletes the space after "Ending". For instance, "Period Ending July
31, 2007" is now "Period BeginningJuly 31, 2007" (Note: no space
betweem "Beginning" and "July" after Replace).

Any advice?

Use string.Replace instead. There is no reason to use Regex.Replace when
you don't have a regular expression.

If you _do_ have a regular expression, but have replaced it in the
example, show the actual code that you are using. It's very hard to find
errors in code that you can't see.
 
Thanks all for the help!

Here's my situation: I have a PDF file containing multiple pages. I'll
need to replace the word for "Period Ending July 31, 2007" on every
single page. The replacement is successful on the pages except for a
few pages where the space is missing and the line is changed to
"Period BeginningJuly 31, 2007".

In the debugger, the word is always successfully replaced. However, it
shows the incorrect result only for a few pages. I think that this is
related to the way the original PDF file was created
 
Back
Top