0

From the URL:

https://www.flightstats.com/v2/historical-flight/TP/1478/2020/11/3/1047614176

I need to get "2020/11/3"

WHAT I HAVE

  • The Regex:
\d\/(\d+\/\d+\/\d+)

it returns: for full match - "8/2020/1/3", for Group 1 - "2020/1/3". I've tested several combinations and tried to simplify it till this version

  • The Javascript:
var myRe = /\d\/(\d+\/\d+\/\d+)/;
var myArray = myRe.exec('${initialurl}');

Being initialurl a variable

PROBLEMS

The javascript returns: "8/2020/11/3,2020/11/3" and I only need/want the group 1 match or if the full match is correct, just that.

CONTEXT

  • Javascript newbie
  • I'm using this in Ui.Vision Kantu
3
  • Regexp protips: debuggex.com and regex101.com Commented Nov 5, 2020 at 17:31
  • If you're using a recent version of JavaScript you can use a lookbehind to match the first \d/ but not include it in the result. Commented Nov 5, 2020 at 17:34
  • 1
    @WashingtonGuedes Albeit it works, that's some woefully inefficient regex. Switch to PHP at regex101 and you'll see that it takes an absurd 2,622 steps to execute that; clocking in at 2ms on average. Commented Nov 5, 2020 at 18:20

1 Answer 1

2

If your URLs are going to reliably be in the format shown then this would do it:

\d{4}\/\d{1,2}\/\d{1,2}

https://regex101.com/r/BqW2lr/1

var initialurl = 'https://www.flightstats.com/v2/historical-flight/TP/1478/2020/11/3/1047614176';
var myRe = /\d{4}\/\d{1,2}\/\d{1,2}/;
var myArray = myRe.exec(initialurl);

console.log(myArray);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Worked like a charm. I had tested using "d{4}" but because sometimes the digits before are also 4, it didn't work as intended. I also tested using "d{2} | d{1}" for the month part since it can have 1 or 2 digits but it also didn't work 100%. With your help I've learned this: "d{1,2}".
@user1128912 You're welcome. Like I mentioned in my answer, this regex is only useful if your URLs are expected to come through in that exact format. So if you have different types of expected URLs then you should add examples of them.
The URL structure is aslways as the one provided :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.