Jeff
Jeff

Reputation: 2248

Regex to search for a word in a string in Visual Studio

I need to search all of my codebase for "Url" and replace it with "URL". If I search for Url in Visual Studio I also get all my variables with "Url" in it.

Anyone have a Regex I can use to only find Url within a quoted string e.g. "Use this Url:"?

Edit

I was looking looking for a quick and dirty way to find designer text and hard coded strings that had Url in the string and change them to URL.

Upvotes: 18

Views: 11669

Answers (5)

DaniCE
DaniCE

Reputation: 2421

I used the following to search only "whole words" (i mean: appearing with an space before an after or immedately after or before the " ):

(("[^"]*[ ]|")Url([ ][^"]*"|"))

For example this matches "test Url" and "Url test" but don't "testUrl".

Upvotes: 1

Kobus Smit
Kobus Smit

Reputation: 1785

If you just quickly want to search for a quoted string you can use the "Use Wildcards" Find Option in Visual Studio.

For example:

"*Url*"

Upvotes: 6

Jeff
Jeff

Reputation: 2248

What I really ended up needing was:

("[^"]*Url[^"]*")

And thanks to the tip from tghw who pointed out the :q shortcut in Visual Studio equates to:

(("[^"]*")|('[^']*'))

I realized I needed to use the first portion to find only the double quoated strings I was looking for.

Both this regex and a standard find with 'Match case' and 'Match whole word' yielded results with some strings I was hoping to not find but eliminated the code with 'Url' in it.

Upvotes: 21

tghw
tghw

Reputation: 25323

Visual Studio has a "quoted string" operator :q. If you search for :qUrl with 'Use: Regular expressions' and 'Match case' on, it should find all instances of "Url" only in strings.

Update: The above is incorrect. :q just searches for a quoted string, but you can't put anything into it. My testing was just showing cases that looked correct, but were just coincidentally correct. I think instead, you want something like:

^(:q*.*)*(("[^"]*Url[^"]*")|('[^']*Url[^']*'))(:q*.*)*$

Upvotes: 9

rpjohnst
rpjohnst

Reputation: 1642

"Use this (Url):", then you can replace $1 (or whatever syntax Visual Studio uses). You may need to escape the quotes, and I'm not sure if Visual Studio lets you parenthesize parts of the regex.

Upvotes: 0

Related Questions