Regular expressions
This time, I will explain the systematic use of regular expressions in Office scripts.
Definition of regular expression
If you use regular expressions in the Office Scripts, define the regular expression literal (//
) enclosed in slash or use the Regexp
object.
In both cases, the same object is created, but if you want to use a variable in a regular expression or dynamically generates a regular expression based on the input from the user, it can be realized only with the Regexp
object instance.
/** A regular expression that only matches 2 -digit numbers */
const regexp1 = /^[0-9]{2}$/;
/** A regular expression that matches the string that starts with「value」*/
const regexp2 = new RegExp(`^value.*`);
Check the match between the regular expression and the string
When using the method RegExp.test
If you simply check whether the regular expression and the specified character string match, use the Regexp.test
method.
Regexp.test
requires a string as an argument, and returns true if it matches the regular expression.
/** A regular expression that only matches 2-digit numbers */
const regexp = /^[0-9]{2}$/;
console.log(regexp.test('23')); // true
console.log(regexp.test('2022')); // false
When using the String.search method
The String.search
method can also check the string.
String.search
can pass the regular expression to the argument and return the matching index (several characters).
/** A regular expression that matches if there are two digits in the string */
const regexp = /[0-9]{2}/;
console.log('Today is 17th'.search(regexp));
Replacement of character strings using regular expressions
To replace the string that matches the regular expression with another string, use the regular expression for the String.replace
method argument.
/** "Value" at the top */
const regexp = new RegExp('^value');
const replaced = 'value-content-value'.replace(regexp, 'item'); // item-content-value
If you attach g
to the end of the regular expression literal, you may look for a matching character string through the entire target character string and match multiple times.
Separation of character strings using regular expressions
To divide the string based on a string that matches the regular expression, use the regular expression for the String.split
method argument.
/** A regular expression that matches the slash */
const regexp = /\//;
const splitted = '2022/3/17'.split(regexp); // ['2022', '3', '17']