Home > Enterprise >  GAS Regex, Can someone turn make this regex to work in App Script?
GAS Regex, Can someone turn make this regex to work in App Script?

Time:12-20

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

CodePudding user response:

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.

  • Related