Rudonja
Rudonja

Reputation: 45

Replacing whole values within a string

I have a string which contains some ids, basically a sql expression within a string. I need to present it to user in a more friendly manner ie. Replace ids with names from the database. The problem is that some ids are single digits and others are 2 digits. So when I search and replace a single digit, it also replaces part of 2 digit strings. For example, if the original string is:

    id not in (2, 3, 4) and id > 22

when I perform a search and replace for 2, both the the numbers 2 and 22 get replaced.

With a regex I can find 2, but when I replace it (regex expression basically looks for number that I want and some possible delimiters like space ,() and such). Is it possible to replace this number but keep those delimiters?

This is what I have now:

Regex.Replace(returnValue
               , String.Format("[,( )]{0}[,( )]", number)
               , replaceValue)

Upvotes: 0

Views: 111

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

The pattern suggested by I4V looks simplest and great to me but you can also try this pattern:

(\d+)(?=[,\)])

The idea behind this pattern is that, sometimes we have numbers in column names like Address1, Address2 so using that will match with them as well. This pattern will not allow these cases.

Hope it will help!

EDIT

List<int> replacements = new List<int>(new int[] { 5 , 6 , 7});
string input = "id not in (2, 3, 4) and id > 22";

foreach(int element in replacements)
   input = Regex.Replace(input,@"(\d+)(?=[,\)])",element.ToString());

Here:

ID 2 will be replaced by 5, 3 will be replaced by 6 and 4 will be replaced by 7. so finall string would look like:

id not in (5, 6, 7) and id > 22

Upvotes: 0

nicolas
nicolas

Reputation: 7668

You need to use negative lookarounds as explained here: Regular expression for 10 digit number without any special characters

For your example:

const string input = "id not in (2, 3, 4) and id > 22";
string result = Regex.Replace(input, @"(?<!\d)(\d{1})(?!\d)", @"--$1--");

And the result:

"id not in (--2--, --3--, --4--) and id > 22"

Upvotes: 0

Chris Moutray
Chris Moutray

Reputation: 18379

Change your regex to user look ahead and look behind - so your pattern looks like this

"(?<=[^0-9]){0}(?=[^0-9])"

Or if you like your code example

Regex.Replace(returnValue
    , String.Format("(?<=[^0-9]){0}(?=[^0-9])", number)
    , replaceValue)

So we're saying:

(?<=[^0-9]) look behind our matched item and make sure it isn't an integer

{0} the matched item

(?=[^0-9]) look ahead of our matched item and make sure it isn't an integer

Upvotes: 0

I4V
I4V

Reputation: 35363

Something like this ?

string input = "id not in (2, 3, 4) and id > 22";
var newstr = Regex.Replace(input, @"\d+", m => GetUserName(m.Value));


string GetUserName(string s)
{
    return ">>" + s  + "<<";
}

Upvotes: 2

Related Questions