PDA

View Full Version : Regular Expressions - Using output?



energy
December 3rd, 2008, 11:49 AM
Hey Guys,


I am trying to add "Newline" before and after beginning of every lesson.
Suppose Input is
var str:String = "Lesson 1 Jobmatching." + "\n" + "This is Job Matching Lesson text" + "\n"+ "Do you know this." + "\n" +"Lesson 2 Basics of FlashDesign." + "\n" + "This is Basics of Flash Design Lesson Text";

Now when you trace str, it will be this.

Lesson 1 Jobmatching.
This is Job Matching Lesson text
Do you know this.
Lesson 2 Basics of FlashDesign.
This is Basics of Flash Design Lesson Text
So i have already written a regular expression which matches this text
var pattern:RegExp = /Lesson+ ([0-9]+) ([a-z]+)*./
Looks Correct...isn't it.
Now I have tried "str.replace"...."str.match" etc but couldn't get the desired output.
This is the output i am looking for:

Lesson 1 Jobmatching.

This is Job Matching Lesson text
Do you know this.

Lesson 2 Basics of FlashDesign.

This is Basics of Flash Design Lesson Text



So how can i achieve this.Any thoughts?
Thanks.

creatify
December 3rd, 2008, 12:21 PM
var str:String = "Lesson 1 Jobmatching. This is Job Matching Lesson text Do you know this. Lesson 2 Basics of FlashDesign. This is Basics of Flash Design Lesson Text";

// if all your text is in one string, you need to use the global flag, and a good idea to use the case insensitive flag
var pattern:RegExp = /Lesson+ ([0-9]+) ([a-z, ]+)*./gi;

// here you can find it matches the lesson titles
var ar:Array = str.match(pattern);
//trace(ar.toString());

//and here you can replace using the found string;
str = str.replace(pattern, "\n\n$&\n");

// the only problem I don't have time to resolve is the first item ends up with two \n\n at the begining, you can strip those out, or maybe there is a way via RegExp
trace(str);

energy
December 3rd, 2008, 01:44 PM
Thanks a lot creatify!

That worked perfectly.

Earlier i was breaking my head with
str = str.replace(pattern, "\n");
like things. Didn't know about the "$&" syntax. Figuring it out now.