Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression Help (Numbers with Decimal)

Status
Not open for further replies.

ljwilson

Programmer
May 1, 2008
65
US
I am trying to create an array with the matched elements from a string. I am not having much success (the result is an empty array). Here is what I got:

Code:
var regpattern = new RegExp("^\d+(\.\d{1,2})?$");
var myarray = new Array;
myarray[21] = "TEXT NOT NEEDED";
myarray[22] = "Diagnosis: Other cardiorespiratory problems-V47.2; OTHER - RHEUMATIC FEVER W/O";
myarray[23] = "HEART INVOLV - 390; Paroxysmal supraventricular tachycardia-427.0; Partial";
myarray[24] = "congenital anomalous pulmonary venous"
myarray[25] = "MORE TEXT NOT NEEDED";

var mystring = myarray.slice(22,25," "); // This works

var stringarray = regpattern.exec(mystring);

What am I doing wrong?
 
Hi

ljwilson said:
[tt]new RegExp("^\d+(\.\d{1,2})?$");[/tt]
[ul]
[li]Inside a string you have to escape the special characters like backslash ( \ ) with a backslash[/li]
[li]You anchored the expression to both the beginning and the end, so it will match only if the entire string matches.[/li]
[/ul]
ljwilson said:
[tt]mystring = myarray.slice(22,25," ");[/tt]
[ul]
[li][tt]Array.slice()[/tt] expects only two parameters[/li]
[li][tt]Array.slice()[/tt] returns an array[/li]
[/ul]
ljwilson said:
[tt]stringarray = regpattern.exec(mystring);[/tt]
[ul]
[li][tt]RegExp.exec()[/tt] expects a string, so the array you passed will be stringified, that will insert commas ( , ) between the elements[/li]
[/ul]


Feherke.
 
Thanks for the help. I see what I did wrong with the SLICE function (somehow I thought it would return a string with the third parameter as the delimiter). What would I need to use for defining that regular expression if I only wanted numbers with or without decimals to be matched?
 
Try somethng like

/[0-9]+\.?[0-9]+?/g


Additionally, exec while it returns an array, it doesn't return it all in one go, you need to call it in a loop until it can find no more matches to get all the possible results.

Code:
var i=0;
var stringarray=new Array();
while(stringarray[i]=regpattern.exec(mystring)){
i++;
}

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top