Jordan Trainor
Jordan Trainor

Reputation: 2438

matching and replacing text in a string while keeping non replaced text

I know how to use Regex.Split() and Regex.Replace(); but not how to keep certain data when replacing.

if I had the following lines of text in a String[] (Split after every ;)

"

using system;
using system.blab;
using system.blab.blabity;

"

how would I loop trough and replace all 'using' to '' but match the whole line 'using (.+;)' for example. and end up with the following (but not just Regex.replace("using", "");) "

<using> system;
<using> system.blab;
<using> system.blab.blabity;

"

Upvotes: 1

Views: 169

Answers (4)

garyh
garyh

Reputation: 2852

This combines 2 of the answers. It wraps word boundaries \b around using to perform a whole words only search and then captures the regex in a back-reference $1

string str = @"using system;
using system.blab;
using system.blab.blabity;";

str = Regex.Replace(str, @"\b(using)\b", "<$1>");

Upvotes: 0

viggity
viggity

Reputation: 15227

This should get you pretty close. You should use a named group for every logical item you're trying to match. In this instance, you're trying to match everything that is not the string "using". You can then use the notation ${yourGroupName} to reference the match in the replacement string. I wrote a tool called RegexPixie that will show you live matching of your content as you type so you can see what works and what doesn't work.

//the named group has the name "everythingElse"
var regex = new Regex(@"using(?<everythingElse>[^\r\n]+)");
var content = new string [] { /* ... */ };

for(int i = 0; i < content[i]; i++)
{
     content[i] = regex.Replace(content[i], "${everythingElse}");
}

Upvotes: 1

Dave Thieben
Dave Thieben

Reputation: 5427

using parens in a Regex instructs the engine to store that value as a group. then when you call Replace, you can reference groups with $n, where n is the number of the group. I haven't tested this, but something like this:

Regex.Replace(input, @"^using( .+;)$", "$1");

Read here for more info

Upvotes: 2

Kamran Shahid
Kamran Shahid

Reputation: 4124

if str is your current string then

            string str = @"using system;
            using system.blab;
            using system.blab.blabity;";
            str = str.Replace("using ", "<using> ");

Upvotes: 3

Related Questions