0

From this page,(What is a good regular expression to match a URL?)

we can use regular expression to match a lot of URL,( it works as testing in regex website. somehow it is not working in GAS(Google App Script ) since using it as

   var rx = 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*)';

     regex= string.match(rx)
     Logger.log(regex)

It always return null as

Info    null

However this regex works on this page https://regexr.com. How can we make it works with GAS?

How can we match something like this in GAS?

https://notifications.example.com/f/g/FB-FnExAZJUxP7fPZCGR4kW9FodXg0X1GBR4wZ0GUaAV0DgL3xUT1K2gBsxnQVcGbzPcydEWIwOgDQ-GiVzMERg5FPGm1Ek6YWnAyElHsz5uqJe5wYYtgQbGuQmW5WxF6E8bu9CfRtBEJ7AWDxWSwfOu__Ahwrwsnw
TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Perhaps it should be `var rx = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*)/`; – Cooper Dec 18 '21 at 00:58
  • Checkout the answers on this page: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url – Cooper Dec 18 '21 at 01:03
  • not really. it returns only two URLs. while it should matched a lot. can you help me match this url ? https://notifications.example.com/f/g/FB-FnExAZJUxP7fPZCGR4kW9FodXg0X1GBR4wZ0GUaAV0DgL3xUT1K2gBsxnQVcGbzPcydEWIwOgDQ-GiVzMERg5FPGm1Ek6YWnAyElHsz5uqJe5wYYtgQbGuQmW5WxF6E8bu9CfRtBEJ7AWDxWSwfOu__Ahwrwsnw – mmmmmmmmmmmmm Dec 18 '21 at 01:07
  • perhaps you need the g flag as in `/g` – Cooper Dec 18 '21 at 01:08
  • Read the links I gave you. I suspect they know more about it than I do. – Cooper Dec 18 '21 at 01:10
  • read the link before posting the question here, Not sure if all my URL starts with notification.domain.com or something else. (since most url started with www.domain.com ) Thank you. – mmmmmmmmmmmmm Dec 18 '21 at 01:15
  • What do you mean by "it returns only two URLs. while it should matched a lot"? Provide the list of urls that should match and what doesn't match. – TheMaster Dec 18 '21 at 10:07

1 Answers1

0

Your code is not working because it is not using a regex. It is simply matching one text string against another.

To make it work, use a regex literal, like this:

const rx = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*)/i;

If you need to use a text string literal for some reason, double escape the text string using \\ in place of \, and apply the RegExp() constructor to make a regex of it.

doubleunary
  • 13,842
  • 3
  • 18
  • 51