Skip to content

Instantly share code, notes, and snippets.

@black7375
Created September 10, 2021 18:22
Show Gist options
  • Save black7375/a352a817d88c08ffd48705228b57604d to your computer and use it in GitHub Desktop.
Save black7375/a352a817d88c08ffd48705228b57604d to your computer and use it in GitHub Desktop.
Regex Builder Prototype
//== RE::ASSERTIONS ============================================================
const WORD_BOUNDARY = String.raw`\b`;
function lookahead(x, y) {
const symbol = "?=";
return x + group(symbol + y);
}
function lookbehind(x, y) {
const symbol = "?<=";
return group(symbol + y) + x;
}
//== RE::CHARACTOR_CLASSES =====================================================
const ALL_CHAR = ".";
const NUM = String.raw`\d`;
const SPACE = String.raw`\s`;
//== RE::GROUP =================================================================
function group(str) {
return "(" + str + ")";
}
function or(...strs) {
return group(strs.join('|'));
}
//== RE::QUANTIFIERS ===========================================================
function count(str, length) {
return str + `{${length}}`;
}
function infinity(str) {
return str + "*";
}
function lazy(str) {
return str + "?";
}
function maybe(str) {
return lazy(group(str));
}
//== RE::CONST =================================================================
const ALL = infinity(ALL_CHAR);
//== DATA ======================================================================
const MONTH_ARR = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// Date
const MONTH = or(...MONTH_ARR);
const DAY = NUM + lazy(NUM);
const YEAR = count(NUM, 4);
// Date Group
const MONTH_DAY = group(MONTH + SPACE + DAY + WORD_BOUNDARY);
const SPACE_YEAR = group(WORD_BOUNDARY + SPACE + YEAR);
// Check
// Before(Not cleanup), const MD_EXIST = maybe(lookahead(MONTH_DAY, lookahead(ALL, SPACE_YEAR)));
// Before(Not cleanup), const SY_EXIST = maybe(lookbehind(SPACE_YEAR, lookahead(MONTH_DAY, "") + ALL));
const MD_EXIST = maybe(lookahead(MONTH_DAY, ALL + SPACE_YEAR));
const SY_EXIST = maybe(lookbehind(SPACE_YEAR, MONTH_DAY + ALL));
const result = RegExp(MD_EXIST + SY_EXIST, "gm");
//== RESULT ====================================================================
console.log(result);
// => /(((Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d\d?\b)(?=.*(\b\s\d{4})))?((?<=((Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d\d?\b).*)(\b\s\d{4}))?/gm
// https://regexr.com/65dfm
// Before Result
// => /(((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d\d?\b)(?=.*(?=\b\s\d{4})))?((?<=(?=(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d\d?\b).*)\b\s\d{4})?/gm
// https://regexr.com/65d56