Thursday 15 May 2014

javascript - Matching regex patterns in order -


I am creating a mini parser that will take images or attachments and later data for one's own use

I can successfully parse my data with my samples, however, the way I am parsing the text, to get the data, two separate matches Runs the ends and pushes into an array.

As a result, the order of data in my last array is not relative to the original text. Here's an example:

Basic Data

  [ATTACH] 1234 [/ ATTACH] [IMG] http://www.google Com / Abc.gif [/ img] [ATTACH] 5678 [/ ATTACH] [IMG] http://www.google.com/def.gif [/ IMG]   

Results ARRAY

  0: http://www.google.com/abc.gif 1: http://www.google.com/def.gif 2: 1234 3 : 5678   

In reality, I would like to show the results array like this

Expected Result ARRAY

  0: 1234 1: http://www.google.com/abc.gif 2: 5678 3: http://www.google.com/def.gif    it's like this There is a small version of code that I use to do this Yes i  
  // container array of images var imagesContainerArray = {}; Var DAC = 0; Var finalized = {}; // Personal images var pattern = / \ [IMG] ([\ s \ S] *?) \ [\ / IMG \] / GI; Match match; While (match = pattern .expe (text)) {finalImageUrl = match [1]; // I am doing other stuff. Containerre [DC] = final image URL; DAC ++; } // personal ATTACH var pattern = / \ [ATTACH] ([\ s \ S] *?) \ [\ / ATTACH \] / GI; Match match; While (match = pattern .expe (text)) {finalImageUrl = match [1]; // I am doing other stuff. Containerre [DC] = final image URL; DAC ++; }    

You can all enter in the same pattern:

  var pattern = / \ [(IMG | ATTACH)] ([\ s \ S] *?) \ [\ 1 1] / gi; Match match; While (match = pattern.ex (text)) {finalImageUrl = match [2]; Image contentar [DAC] = final image URL; DAC ++; }   

To apply different treatment according to the tag name, you can use a switch / case statement. Example:

  var pattern = / \ [(IMG | ATTACH)] ([\ s \ S] *?) \ [\ 1 1] / gi; Match match; While (match = pattern.ex (text)) {finalImageUrl = match [2]; Switch (match [1]. Toucherace ()) {case "IMG": ... break; Case "ATTACH": ... break; ...} imagesContainerArray [daC] = final image URL; DAC ++; }    

No comments:

Post a Comment