0

I am a regex noob and I try this for a long time.

case1: postgres://123:123@localhost/123
case2: postgres://123:123@integration/123

I am trying to find a regex that matches after @ and before /

For case 1 will give me localhost, case 2 will give me integration

Thanks!

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Paul
  • 13
  • 3
  • Duplicate of this one: https://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud – Nick Oct 12 '17 at 18:38
  • 2
    If you have tried this for a long time, you certainly have something to show that you've tried, right? – Tomalak Oct 12 '17 at 18:38
  • so this (?=\@)(.*?)(?=\/) gave me @localhost which still include @. I also have tried (?:\@)(.*?)(?=\/) and got the same result. – Paul Oct 12 '17 at 18:46
  • Try `.*@\K.*(?=\/)` – CAustin Oct 12 '17 at 18:53
  • Tip: If you don't get it to work with regex, think if you can use something else. In this case, splitting on `@` and then on `/` would work. – Tomalak Oct 12 '17 at 19:07

2 Answers2

0

Just process the match to remove the delimiter(s). There is not much else you can do since JavaScript regex doesn't support lookahead. This should do it.

var strs = ["postgres://123:123@localhost/123", "postgres://123:123@integration/123"];
strs.forEach(str => console.log(str.match(/(?=@)[^\/]+/)[0].substr(1)));

What this does is to return a match that includes the @ and then process that match to remove the delimiter.

You may want to check if there are any matches before you do this to avoid exceptions.

Titus
  • 22,031
  • 1
  • 23
  • 33
0

var test = [
    'postgres://123:123@localhost/123',
    'postgres://123:123@integration/123'
];
console.log(test.map(function (a) {
  return a.match(/@(\w+)/)[1];
}));
Toto
  • 89,455
  • 62
  • 89
  • 125