DamianD
DamianD

Reputation: 1

Regular Expression in Google Apps Script 2

I am having a text file and need to extract words and figures out of it. The Script searches for a keyword and takes the word/figure after the keyword.

This is where i get the result from filter:

var ergebnis=text.match(filter[i]);

These are the regular expressions:

var filter=[/ISIN (\w*)/g, /STK (\w*)/g , /(Kurs) EUR/g];

The regular expression works with the single words ISIN and STK, but fails with the expression Kurs EUR.

I have tried various expressions without getting a match. What am I doing wrong?

Upvotes: 0

Views: 2295

Answers (1)

ctwheels
ctwheels

Reputation: 22817

Brief

You're using match() instead of exec(): See this post and this post for more information.

From match() documentation:

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

From exec() documentation:

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.


Code

Method 1 - Using exec()

The snippet below shows how to use exec() instead of match() to output the matched strings and their respective groups.

var array = [
  "ISIN Something",
  "STK Something_2",
  "Kurs EUR"
]
var filter=[
  /ISIN (\w*)/g,
  /STK (\w*)/g ,
  /(Kurs) EUR/g
];

array.forEach(function(s) {
  filter.forEach(function(f) {
    var m = f.exec(s)
    if (m) {
      console.log(`String: ${m[0]}\nGroup: ${m[1]}`)
    }
  })
})

Method 2 - Removing g flag

The snippet below shows how to use match() to output the matched strings and their respective groups by removing the g modifier. As per the documentation (quoted in the Brief section), this will return the same result as RegExp.exec().

var array = [
  "ISIN Something",
  "STK Something_2",
  "Kurs EUR"
]
var filter=[
  /ISIN (\w*)/,
  /STK (\w*)/ ,
  /(Kurs) EUR/
];

array.forEach(function(s) {
  filter.forEach(function(f) {
    var m = s.match(f)
    if (m) {
      console.log(`String: ${m[0]}\nGroup: ${m[1]}`)
    }
  })
})

Upvotes: 2

Related Questions