October 27, 2022
TestsSource
- Ways to create regexps (objects, literal, ...), (how) do they differ?
- RegExp groups
- What methods are on a regexp?
Source Code
The source code we wrote during the event.
regexp.spec.js
import {strict as assert} from 'assert';
describe('Ways to create regexps (objects, literal, ...), (how) do they differ?', () => {
it('a regexp is of type object', async () => {
const regexp = /./;
assert.equal(typeof regexp, 'object');
});
it('a regexp is an instance of RegExp', () => {
const regexp = /./;
assert(regexp instanceof RegExp);
});
it('a constructed regexp returns the same result as the literal', () => {
const regexpLiteral = /abc/;
const regexpConstruct = new RegExp('abc');
assert.deepEqual(regexpLiteral.exec('abc'), regexpConstruct.exec('abc'));
});
});
describe('RegExp groups', () => {
it('a group does not effect the matched pattern', () => {
const regexp = /(ab)c/; // the (...) is the group
const result = regexp.exec('abcd');
assert.deepEqual(result[0], 'abc');
});
it('a very simple group shows up in our match result, on index 1 (first group)', () => {
const regexp = /(ab)c/;
const result = regexp.exec('abcd');
assert.equal(result[1], 'ab');
});
it('three groups are returned in index 1,2 and 3 of the match result', () => {
const regexp = /(a)(b)(c)/;
const result = regexp.exec('abcd');
assert.equal(result[1], 'a');
assert.equal(result[2], 'b');
assert.equal(result[3], 'c');
});
it('using a group we can split a SIMPLE email', () => {
const regexp = /(.+)@(.+)/;
const result = regexp.exec('user@name.com');
assert.deepEqual(Array.from(result), ['user@name.com', 'user', 'name.com']);
assert.equal(result[0], 'user@name.com');
assert.equal(result[1], 'user');
assert.equal(result[2], 'name.com');
});
it('a named group is in the `groups` property of the match result', () => {
const regexp = /(?<name>ab)/;
const result = regexp.exec('abc');
assert.equal(result.groups.name, 'ab');
});
});
describe('What methods are on a regexp?', () => {
it('a regexp can match itself', () => {
const regexp = /abc/;
const result = regexp.exec(regexp);
assert.deepEqual(result[0], 'abc');
});
});