off_script
off_script

Reputation: 1

How to use Regex to parse variable length string in Google Application Scripts

Trying to extract the alphanumeric parts of a variable length string with a known pattern using Regex in Google Application Scripts. Pattern repeats n times as follows (XXXs are groups of Alphanumeric characters): XX-XXX-X-XX-XX-........ for example ABC-AB or ABCD-AB-ABC-AA I want to extract the alphanumeric parts into an Array if possible like e[0] = ABCD e[1] = AB e[2] = ABC .....

I tried repeated \w+ but that requires knowing the possible lengths of string. See below. Is there a way for Regex to process varying size strings? See my example code below:

var data1 = 'ABC-AB';
var data2 = 'ABCD-AB-ABCD-AA';

var regex1 = new RegExp(/(\w+)-(\w+)/); 
var regex2 = new RegExp(/(\w+)/);

e = regex1.exec(data1); //stores ABC and AB as separate array elements.

This is fine but won't work on a string with larger size

e = regex2.exec(data2); //stores ABCD only as a single array element "ABCD"

Upvotes: 0

Views: 95

Answers (1)

Bohemian
Bohemian

Reputation: 424983

To match any length of kebab case letters:

var regex1 = new RegExp(/\w+(-\w+)*/)

For each of the matches found, split the result on dashes to get your array.

var array = found.split("-")

Upvotes: 1

Related Questions