c# - Replace part of a string with new value -


i've got scenario, wherein need replace string literal new text.

for example, if string "01hw128120", first check if text contains "01hw" if yes, replace string "machineid-".

so wanted "01hw128120" "machineid-128120". string "1001hw128120" - in case require replace "1001hw" "machineid-" tried below code snippet, not work expectation.

string sampletext = "01hw128120"; if(sampletext.contains("01hw"))   sampletext = sampletext.replace("01hw","machineid-"); 

any suggestion of great me.

few possible search values

if there few possible combinations, can multiple tests:

string value = "01hw128120"; string replacement = "machineid-";  if( value.contains( "01hw" ) ) {     value = value.replace( "01hw", replacement ); } else if( value.contains( "1001hw" ) ) {     value = value.replace( "1001hw", replacement ); }  assert.areequal( "machineid-128120", value ); 

many possible search values

of course, approach becomes unwieldy if have large quantity of possibilities. approach keep of search strings in list.

string value = "01hw128120"; string replacement = "machineid-";  var tokens = new list<string> {     "01hw",      "1001hw"      // n number of potential search strings here };  foreach( string token in tokens ) {     if( value.contains( token ) ) {         value = value.replace( token, replacement );         break;     } } 

"smarter" matching

a regular expression well-suited string replacement if have manageable number of search strings perhaps need not-exact matches, case-insensitivity, lookaround, or capturing of values insert replaced string.

an extremely simple regex meets stated requirements: 1001hw|01hw.

demo: http://regexr.com?34djm

a smarter regex: ^\d{2,4}hw

  • assert position @ start of string
  • match 2-4 digits
  • match value "hw" literally

see also: regex.replace method


Comments

Popular posts from this blog

asp.net mvc 3 - Using mvc3, I need to add a username/password to the sql connection string at runtime -

kineticjs - draw multiple lines and delete individual line -

thumbnails - jQuery image rotate on hover -