JatSing
JatSing

Reputation: 4987

Find and replace with regular expression in Visual Studio 10

For example I have the following strings :

abc Edit worksheet xyz
abc Edit contract xyz
abc Edit xyz

Now I want to replace only string "Edit" into "Detail", "Edit worksheet" "Edit contract" still remain the same. The result should be:

abc Edit worksheet xyz
abc Edit contract xyz
abc Detail xyz

I would appreciate if you can make an explain.

Upvotes: 1

Views: 433

Answers (6)

gingo
gingo

Reputation: 488

You can do a trick like this:

  1. replace in all your code "Edit worksheet" with "ABC123"
  2. replace in all your code "Edit contract" with "DEF456"
  3. replace in all your code "Edit" with "Detail"
  4. replace in all your code "ABC123" with "Edit worksheet" (restore old strings)
  5. replace in all your code "DEF456" with "Edit contract" (restore old strings)

in other words you hide "Edit worksheet" and "Edit contract" with 2 fantasy and unique strings, then make your requested replace and finally restore your original text.

Upvotes: 1

gingo
gingo

Reputation: 488

I would not use regular expression, but just simple string methods.

I would do a loop through all the lines looking for "Edit" and when I found it, then check if the following word is "worksheet" or "contract": in this last case I do not replace the word.

I write an example in a meta-language:

While not EnfOfLine
   if "'Edit' is found" then
      if not "next word is 'worksheet' or 'contract'"
          then replace ("Edit", "Detail")
      end if
   end if
   go next line
end while

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75272

To match "Edit" only if it's not followed by the word "worksheet" or "contract", you can use this:

<Edit>~(:b+(worksheet|contract))
  • < and > match the beginning and end of a word, respectively.

  • ~(...) is what most regex flavors call a negative lookahead.

  • :b+ matches one or more spaces or tabs in any combination.

These constructs are available in many regex flavors, but Visual Studio uses its own, extremely unusual syntax.

Upvotes: 3

Sergey Vlasov
Sergey Vlasov

Reputation: 27940

In Visual Studio Find and Replace dialog:

Find what: Edit ~(worksheet|contract) Replace with: Detail

Upvotes: 1

anthony sottile
anthony sottile

Reputation: 70233

I don't think you need regex?

Can't you just replace "abc Edit xyz" with "abc Detail xyz"

Or is abc and xyz not always the same?

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50245

Assuming it's the only word on the line, search for:

^Edit$

and replace with

Detail

^ matches the start of a line.
$ matches the end of a line.

Upvotes: 1

Related Questions