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!

Parsing a string with RegExp 1

Status
Not open for further replies.

Supra

Programmer
Dec 6, 2000
422
US
I'm going insane trying to figure out why this RegExp is cutting my string in half. The purpose of the pattern is to replace any "tags" within a "%%string%%" tag.
Code:
var data = '"%%string%%hello %%number%%1%%%end%%% and hello %%number%%2%%%end%%%.%%%end%%%"';
var pattern = /(?:"%%string%%)((.*?)(%%number%%([0-9])%%%end%%%))+/g;
var result = data.replace(pattern,'"%%string%%$2$4');
Expected Result: "%%string%%hello 1 and hello 2.%%%end%%%"
Actual Result: "%%string%% and hello 2.%%%end%%%"

Any ideas?
 
Hi

You have only one '%%string%%' so the pattern will match only 1 time. But you allow group 1 to match 1 or more times, so that will match 2 times.
Code:
var pattern = /(?:"%%string%%)((.*?)(%%number%%([0-9])%%%end%%%))/g;

var result=data;

while (result.match(pattern)) result=result.replace(pattern,'"%%string%%$2$4');

Feherke.
 
Giving a star because it works, but isn't there any way to do in a single shot? Seems like there should be.
 
This will do, but, maybe you need something to assure prefix %%string%%?
[tt]
var pattern=/%%number%%([0-9])%%%end%%%/g;
var result = data.replace(pattern,'$1');[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top