0

My string <a href="/?an=mb_artist&uid=40574" target="_blank">Maroon 5</a> - <a href="/?an=mb_track&uid=151311">One More Night</a>

Try to get content of a tags with regexp /<a.*>(.*)<\/a>/ig , but get only "One More Night", how to get "Maroon 5" and "One More Night" ?

socm_
  • 783
  • 11
  • 28
  • It might help to show us the code you are running - the problem is as likely to be the way you are retrieving the results as it is with the expression itself. – glenatron Aug 22 '14 at 11:42
  • 2
    [You can't parse HTML with regex.](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Ortiga Aug 22 '14 at 11:43
  • @Andre you can, but it's not adviced to do it with regex. – Andrei Sfat Aug 22 '14 at 11:59

2 Answers2

1

In javascript you have got much more beautifull means of working with markup DOM.

For example jQuery library...

See my fiddle example: http://jsfiddle.net/3kfcp156/

    $(document).ready(function() {
        $('a').each(function(item,idx) {
            alert($(this).text());
        });
     });
michalh
  • 2,907
  • 22
  • 29
0

Add a question-mark after the *. Without an question-mark the regular expressions tries to match as many as characters as possible (greedy mode). With the question-mark as little as possible.

/<a.*?>(.*?)<\/a>/ig

Without:

    /<a.*>(.*)<\/a>/ig
//   ^^^^^ this part matches: <a href="/?an=mb_artist&uid=40574" target="_blank">Maroon 5</a> - <a href="/?an=mb_track&uid=151311">

Demo: http://regex101.com/r/hX1aD1/2

Update:

var myRe = /<a.*?>(.*?)<\/a>/ig;
var myArray;
while ((myArray = myRe.exec(str)) !== null)
{
  var content = myArray[1];
  // do something with it
}
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29