scaryguy
scaryguy

Reputation: 7950

How to to extract a string between two characters?

These are my strings:

there_is_a_string_here_1_480@1111111
there_is_a_string_here_1_360@1111111
there_is_a_string_here_1_180@1111111

What I want to do is extracting 180, 360 and 480 from those strings.

I tried this RegEx _(.*)@ but no chance.

Upvotes: 0

Views: 106

Answers (4)

Felipe C Vieira
Felipe C Vieira

Reputation: 56

try this:

(?<=(?!.*))(.*)(?=@)

Use lookbehind (?<=) and look ahead (?=) so that "_" and "@" are not included in the match.

(?!.*) gets the last occurence of "_".

(.*) matches everything between the last occurence of "_" and "@".

I hope it helps.

Upvotes: 0

sideroxylon
sideroxylon

Reputation: 4416

You just want the capture group:

var str = 'there_is_a_string_here_1_180@1111111';
var substr = str.match(/_(\d*)@/);
if (substr) {
  substr = substr[1];
  console.log(substr);
}

//outputs 180

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

Try this

    var str = "there_is_a_string_here_1_480@1111111";
    var matches = str.match(/_\d+@/).map(function(value){return value.substring(1,value.length-1);});
document.body.innerHTML += JSON.stringify(matches,0,4);

Upvotes: 1

aelor
aelor

Reputation: 11116

you almost got it

_(\d{3})@

you need to do a match on digits, or else the string will also get selected because of the other underscore.

Ofcourse your match will be in \1

Upvotes: 1

Related Questions