Jump to content

Help with RegEx


ShadowMage

Recommended Posts

Hey guys, I need a little help on this one.What I'm trying to do is find a string value inside another string. Each string value is delimited by a semicolon. So it might look something like this:var str = "Part_Rafters_0__1=>1219;Part_Purlins_0__1=>1219;Part_Purlins_1__1=>";I need to be able to find and remove the "Part_Purlins_0__1=>1219" part plus one of the semicolons (either the starting or ending one, not both). This is the part I'm having trouble with. I came up with this regex:var regex = new RegExp("(?:[;])?Part_Purlins_0__1=>[^;]*(?:[;])?");but it matches both semicolons, so when I use the replace method like so:alert(str.replace(regex, ''));I get an alert with "Part_Rafters_0__1=>1219Part_Purlins_1__1=>" in it instead of "Part_Rafters_0__1=>1219;Part_Purlins_1__1=>" like I want. So I tried using conditional subpatterns and came up with this regex:var regex = new RegExp("([;])?Part_Purlins_0__1=>[^;]*(?(1)|([;])?)");Trouble is, this one doesn't parse. My script just aborts on that line. No error messages, either (which I thought to be rather odd).I'm certain that the problem is here: (?(1)|([;])?)But I'm not sure how to fix it. If the first semicolon matches I don't want to match the second one, which is why I left the spot in front of the '|' blank, and if the first one doesn't match, I need it to match the second one. I also tried it like this: (?(1)()|([;])?) but that gives me the same result (script aborts).Also, both semicolons need to be optional, since the delimited string could potentially contain just "Part_Purlins_0__1=>1219"Can somebody help me, please?

Link to comment
Share on other sites

I think I got it! My regex now looks like this:var regex = new RegExp("([;])?Part_Purlins_0__1=>[^;]*(?!(1)([;])?)");The important change being the '!' in (?!(1)([;])?)I knew there had to be a way to write a negation or negative conditional or whatever the heck you want to call it. :)

Link to comment
Share on other sites

Shucks...Seems it doesn't work afterall. The following string isn't properly matched:var str = "Part_Purlins_0__1=>1219;Part_Purlins_1__1=>";When I remove the matched portion I'm left with ";Part_Purlins_1__1=>"The semicolon shouldn't be there...:)

Link to comment
Share on other sites

I'm beginning to think that JavaScript doesn't support conditional patterns...:)...bummer.I'm sure there might be a way to use assertions, but I just can't wrap my head around assertions. Their proper usage eludes me.Guess I'm probably going to have to do it the hard way (??only way??) and use multiple regex's and if statements to first check for ";pattern" then "pattern;" and finally just "pattern"

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...