views:

50

answers:

2

I have a string that is similar to a path, but I have tried some regex patterns that are supposed to parse paths and they don't quite work.

Here's the string

f|MyApparel/Templates/Events/

I need the "name parts" between the slashes.

I tried (\w+) but the array came back [0] = "f" and [1] = "f".

I tested the pattern on http://www.gskinner.com/RegExr/ and it seems to work correctly.

Here's the AS code:

var pattern : RegExp = /(\w+)/g;
var hierarchy : Array = pattern.exec(params.category_id);
params.name = hierarchy.pop() as String;
+1  A: 

I don't know between which two slashes you want but try

var hierarchy : Array = params.category_id.split(/[\/|]/);

[\/|] means a slash or a vertical bar.

KennyTM
+1. Although @Tomalak answered the OPs question about using RegExp, I think this is a much better solution for the problem... and actually does still use RegExp. :)
sberry2A
+2  A: 

pattern.exec() works like in JavaScript. It resets the lastIndex property every time it finds a match for a global regex, and next time you run it it starts from there.

So it does not return an array of all matches, but only the very next match in the string. Hence you must run it in a loop until it returns null:

var myPattern:RegExp = /(\w+)/g;  
var str:String = "f|MyApparel/Templates/Events/";

var result:Object = myPattern.exec(str);
while (result != null) {
  trace( result.index, "\t", result);
  result = myPattern.exec(str);
}
Tomalak
+1 - Correct about having to loop. However, I would add that this problem is better solved using split instead of RegExp.
sberry2A
For this specific problem, agreed. Other, similar problems may not be so easily solved with `split()`. The general misconception in the question was about how `pattern.exec()` worked, and this was what I wanted to correct.
Tomalak