Vitim.us
Vitim.us

Reputation: 22128

Why this regex is causing infinity loop?

function listPlayers(subject){
    var players=[];

    var myregexp = /(\S*)(?:,\s|$)/g;
    var match = myregexp.exec(subject);
    while (match != null) {
         players.push(match[1]);
         match = myregexp.exec(subject);
    }
    return players;
}

The string I'm trying to match is like this �r Henderson�r�f, Pedrin�r�f, �c~�lArthur�r�f, John�r�f

The output I expect is an array like this ['Henderson�r�f', 'Pedrin�r�f', '�c~�lArthur�r�f', 'John�r�f']

What I don't understand is on regex buddy everything seems ok. enter image description here

Upvotes: 1

Views: 324

Answers (2)

MikeM
MikeM

Reputation: 13631

Just for interest, a perhaps simpler way using a zero-width positive lookahead assertion:

function listPlayers( subject ) {
    return subject.match( /\S+(?=,\s|$)/g );
}

Upvotes: 2

Barmar
Barmar

Reputation: 780842

Try changing the regexp to:

var myregexp = /(\S+)(?:,\s|$)/g;

I think the loop may be because it repeatedly matches an empty string at the end.

Since I don't think you're interested in getting zero-length names, this is probably a better regexp in general.

Upvotes: 5

Related Questions