1//Declare Reg using slash
2let reg = /abc/
3//Declare using class, useful for buil a RegExp from a variable
4reg = new RegExp('abc')
5
6//Option you must know: i -> Not case sensitive, g -> match all the string
7let str = 'Abc abc abc'
8str.match(/abc/) //Array(1) ["abc"] match only the first and return
9str.match(/abc/g) //Array(2) ["abc","abc"] match all
10str.match(/abc/i) //Array(1) ["Abc"] not case sensitive
11str.match(/abc/ig) //Array(3) ["Abc","abc","abc"]
12//the equivalent with new RegExp is
13str.match('abc', 'ig') //Array(3) ["Abc","abc","abc"]
1'string'.match(/regex/);
2 console.log('The 1quick5'.match(/[0-9]/g)); // ['1', '5']
3
4/regex/.test('string');
5console.log(new RegExp('foo*').test('table football')); //true
6
7
1you want to achieve a case insensitive match for the word "rocket"
2surrounded by non-alphanumeric characters. A regex that would work would be:
3
4\W*((?i)rocket(?-i))\W*
1const regex = /([a-z]*)ball/g;
2const str = "basketball football baseball";
3let result;
4while((result = regex.exec(str)) !== null) {
5 console.log(result[1]);
6 // => basket
7 // => foot
8 // => base
9}
1// regex_match example
2#include <iostream>
3#include <string>
4#include <regex>
5
6int main()
7{
8 if (std::regex_match("subject", std::regex("(sub)(.*)")))
9 std::cout << "string literal matched\n";
10
11 const char cstr[] = "subject";
12 std::string s("subject");
13 std::regex e("(sub)(.*)");
14
15 if (std::regex_match(s, e))
16 std::cout << "string object matched\n";
17
18 if (std::regex_match(s.begin(), s.end(), e))
19 std::cout << "range matched\n";
20
21 std::cmatch cm; // same as std::match_results<const char*> cm;
22 std::regex_match(cstr, cm, e);
23 std::cout << "string literal with " << cm.size() << " matches\n";
24
25 std::smatch sm; // same as std::match_results<string::const_iterator> sm;
26 std::regex_match(s, sm, e);
27 std::cout << "string object with " << sm.size() << " matches\n";
28
29 std::regex_match(s.cbegin(), s.cend(), sm, e);
30 std::cout << "range with " << sm.size() << " matches\n";
31
32 // using explicit flags:
33 std::regex_match(cstr, cm, e, std::regex_constants::match_default);
34
35 std::cout << "the matches were: ";
36 for (unsigned i = 0; i < cm.size(); ++i) {
37 std::cout << "[" << cm[i] << "] ";
38 }
39
40 std::cout << std::endl;
41}