0

I need to get two parts (username/gistid and filename) from a github gist url.

Sofar i got this:

  const gisturl = "https://gist.github.com/vanaf1979/329abed564c2ba10eda29a53b399ac69#file-parse-wp-rest-api-1-parse-js";
  const myRegexp = /\.com\/+(.*)?#file-(.*)/gi;
  const matches = myRegexp.exec(gisturl);
  console.log(matches);

whithc gives me

0: ".com/vanaf1979/329abed564c2ba10eda29a53b399ac69#file-parse-wp-rest-api-1-parse-js"
1: "vanaf1979/329abed564c2ba10eda29a53b399ac69"
2: "parse-wp-rest-api-1-parse-js"

So far so good, except the filename (#file-parse-wp-rest-api-1-parse-js) is optional and if i remove it from the string the regex doest match anymore.

So i need the regex to match both case with or without the filename.

Any help would be very appreciated.

0

1 Answer 1

2

You could change the first part to use a negated character class instead [^#]+ matching any char except a #

Then you can make the second part optional and keep the capturing group for the part that comes after file-

Note that you can omit the plus sign after the forward slash \/+

\.com\/([^#]+)(?:#file-(.*))?

Regex demo

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

1 Comment

That works like a charm! Thanks, Also for the explenation! You rock! :p

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.