0

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;
0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 - Correct about having to loop. However, I would add that this problem is better solved using split instead of RegExp.
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.
1

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.

1 Comment

+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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.