Seemingly simple regex question

  • Thread starter Thread starter sb
  • Start date Start date
S

sb

I'm using the following regex expression where "searchword" is a string:
string regrexstr = @"( |^)\b" + searchword + @"+( |\b)"

My goal is to use this string to ultimately replace all occurances of
searchword as long as:
a) it has a preceeding space or it's the beginning of a line AND
b) it is suffixed with a space or a newline character

The problem right now is that using the above string and calling
Regex.Replace also replaces the leading/trailing spaces. I want the spaces
to count during the match, but be ignored during the replace. Is that
easily do-able?

I'm probably going about this the wrong way. In short, I want to do a word
replacement throughout a large file.

TIA!
-sb
 
Hi sb,

This should be solvable by using LookArounds. A LookAround is a
non-capturing condition. That is, it defines a match without consuming the
characters being "looked-ahead" or "looked-behind."

(?=expression) Positive LookAhead. Match must be followed by the
expression.
(?<=expression) Positive LookBehind. Match must be preceded by the
expression.
(?!expression) Negative LookAhead. Match must NOT be followed by the
expression.
(?<!expression) Negative LookBehind. Match must NOT be followed by the
expression.

Example:

(?<= )Some words(?!\.)

This means that the phrase "Some words" must be preceded by a space, and
must NOT be followed by a period:

Some words.
Some words? *Match*
Some words.
Some words

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

Orange you bland I stopped splaying bananas?
 
Thanks! I was hoping it would be this simple :)

Kevin Spencer said:
Hi sb,

This should be solvable by using LookArounds. A LookAround is a
non-capturing condition. That is, it defines a match without consuming the
characters being "looked-ahead" or "looked-behind."

(?=expression) Positive LookAhead. Match must be followed by the
expression.
(?<=expression) Positive LookBehind. Match must be preceded by the
expression.
(?!expression) Negative LookAhead. Match must NOT be followed by the
expression.
(?<!expression) Negative LookBehind. Match must NOT be followed by the
expression.

Example:

(?<= )Some words(?!\.)

This means that the phrase "Some words" must be preceded by a space, and
must NOT be followed by a period:

Some words.
Some words? *Match*
Some words.
Some words

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

Orange you bland I stopped splaying bananas?
 
Back
Top