简体   繁体   中英

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)

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  + "<<";
}

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM