Javascriptならよく利用される関数はtest(), match()です。
const assert = require('assert').strict;
// 特定の文字列が存在するか
assert.ok(/\d{4}/.test('Today 2022 football.'));
assert.ok(/^\d{4}/.test('Today 2022 football.') === false);
assert.ok(/^\d{4}/.test('2022 football.'));
assert.ok(/^\d{4}$/.test('2022 football.') === false);
assert.ok(/^\d{4}$/.test('2022'));
// 特定の文字列を抽出する
// [ '2022', index: 6, input: 'Today 2022 football.', groups: undefined ]
console.log('Today 2022 football.'.match(/\d{4}/));
// [ '2022', '1234' ] only matched value return if global match
console.log('Today 2022 football. 12345'.match(/\d{4}/g));
// [ 'Today 2022', 'football 1234' ] no group info
console.log('Today 2022 football 12345'.match(/\w+ (\d{4})/g));
// Get group values
const allMatches = 'Today 2022 football 12345'.matchAll(/\w+ (\d{4})/g);
for (const match of allMatches) {
console.log(match);
assert.ok(/^\d{4}$/.test(match[1]));
}
Pythonでよく利用される関数はsearch()です。
import re
# match() check from the beginning
# <re.Match object; span=(0, 4), match='2022'>
print(re.match(r'\d{4}', '2022 football.'))
assert re.match(r'\d{4}', 'Today 2022 football.') is None
# <re.Match object; span=(0, 11), match='Today 2022 '>
assert re.match(r'\w+ \d{4} ', 'Today 2022 football.')
assert re.fullmatch(r'\d{4}','2012')
assert re.fullmatch(r'\d{4}','2012 year') is None
# search through the text
print('------------search------------')
assert re.search(r'\d{4}', '1234Today 2022 football.').group() == '1234'
assert re.search(r'\d{5}', '1234Today 2022 football.') is None
assert re.search(r'[a-zA-Z]+ (\d{4})', '1234Today 2022 football.').group() == 'Today 2022'
assert re.search(r'[a-zA-Z]+ (\d{4})', '1234Today 2022 football.').group(1) == '2022'
# ignore group
for m in re.findall(r'[a-zA-Z]+ (\d{4})','Hi 1234 Today 2022 football.' ):
print(m)
Pythonのmatchは文字列の先頭からチェックするので、注意しよう。