user4284509
user4284509

Reputation:

Javascript regex negation give the incorrect result

For example my data like this

AAAG        ( 382 TO 385 )( 1729 TO 1732 )( 2405 TO 2408 )( 3759 TO 3762 )
AAAKSKSAL       ( 1941 TO 1949 )( 3973 TO 3981 ) AAAKSKSAL

I tried below script

var xa = "AAAKSKSAL     ( 1941 TO 1949 )( 3973 TO 3981 )";
var regex = /([^\dTO\s\(\)]+)/g;
var matches =  [];
matches = regex.exec(xa); 
alert(matches);

My string contain only one data but it alerts AAAKSKSAL,AAAKSKSAL.

Or Else

var xa = "AAAKSKSAL    ( 1941 TO 1949 )( 3973 TO 3981 ) ( 1941 TO 1949 )( 3973 TO 3981 ) AAAKSKSAL AAAKSKSAL AAAKSKSAL";

It alerts AAAKSKSAL,AAAKSKSAL. But in previous example my input data contain four matched elements. But it result only two. What is the mistake of my regex?

But i tried the same concept in perl this is works fine

 $s = "AAAKSKSAL( 1941 TO 1949 )( 3973 TO 3981 )  AAAKSKSAL";  
 @ar = $s=~m/([^\dTO\s\(\)]+)/g;  
 print @ar

Upvotes: 1

Views: 51

Answers (2)

anubhava
anubhava

Reputation: 785128

Rather than match you should use replace and remove unwanted text:

xa = xa.replace(/\s*\(\s*\d+\s+TO\s+\d+\s*\)\s*/ig, '');

RegEx Demo

Upvotes: 0

Unglückspilz
Unglückspilz

Reputation: 1890

Your regex is fine but you're using expression.exec() incorrectly. Instead of this:

var matches =  [];
matches = regex.exec(xa); 
alert(matches);

Try this:

var matches = [];

while ((m = regex.exec(xa)) !== null) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    matches.push(m[0]);
}

alert(matches);

Upvotes: 1

Related Questions