0

I want to replace the numbers in the string with _number.We have to fetch the numbers only that dont begin with a character and replace them with a underscore . Requirement : I have a string, so while processing I want to replace constants with _Constant. example string :"(a/(b1/8))*100" output expected :"(a/(b1/_8))*_100"

Please suggest how to do this in asp.net code behind.

Thanks in advance.

imran
  • 21
  • 1

3 Answers3

2

You'll need a regular expression and the replace function:

var str = '(a/(b1/8))*100';
alert( str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2') );

So, what's going on?

  • The /'s mark the beginning and end of the regular expression (the tool best suited to this task).
  • [^a-zA-Z0-9] means "nothing which is a letter or a number".
  • [0-9] means "a digit".
  • Together, they mean, "something which is not a letter or a number followed by a digit".
  • The g at the end means "find all of them".
  • The () groups the regular expression into two parts $1 and $2
  • The '$1_$2' is the output format.

So, the expression translates to:

Find all cases where a digit follows a non-alphanumeric. Place a '_' between the digit and the non-alphanumeric. Return the result.

Edit

As an aside, when I read the question, I had thought that the JS function was the desired answer. If that is not the case, please read rkw's answer as that provides the C# version.

Edit 2

Bart brought up a good point that the above will fail in cases where the string starts with a number. Other languages can solve this with a negative lookbehind, but JavaScript cannot (it does not support negative lookbehinds). So, an alternate function must be used (a NaN test on substr( 0, 1 ) seems the easiest approach):

var str = '(a/(b1/8))*100';
var fin = str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2');
if( !isNaN( fin.substr( 0, 1 ) ) ) fin = "_" + fin;
alert( fin );
Community
  • 1
  • 1
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
1

Same as cwallenpoole's, just in C# code behind

string str = '(a/(b1/8))*100';
str = Regex.Replace(str, '([^a-zA-Z])([0-9])', '$1_$2');

Updated:

string str = "(a/(b1/8))*100";
str = Regex.Replace(str, "([^a-zA-Z0-9]|^)([0-9])", "$1_$2");
rkw
  • 7,287
  • 4
  • 26
  • 39
0

Why not try regular expressions: That is:

search for the regex: "[0-9]+" & replace with "_ + regex."

ie.

String RegExPattern = @"[0-9]+";
String str = "(a/(b1/8))*100";
Regex.Replace(str, RegExPattern, "_$1");

Source: http://msdn.microsoft.com/en-us/library/ms972966.aspx

Hope that helps ya some!

Syndacate
  • 637
  • 1
  • 7
  • 15
  • You forgot about the restriction "numbers only that dont begin with a character" (by which he probably means a "word character", or non-punctuation, something like that). – bart Aug 09 '11 at 06:24