Skip to content

Instantly share code, notes, and snippets.

@bdashore3
Last active July 3, 2023 22:27
Show Gist options
  • Save bdashore3/d3b81917a5d4954fa92e2ea026d5fdfd to your computer and use it in GitHub Desktop.
Save bdashore3/d3b81917a5d4954fa92e2ea026d5fdfd to your computer and use it in GitHub Desktop.
ST regex engine POC.
// Goal: Provide regex replacement with any regex string
// Advantages:
// - Lots of flexibility. Any regex string can be used
// - Strings with the same delimiter can be used
// Disadvantages:
// - Requires the user to know how regex works
// - More complicated UI
// - Can become confusing, fast.
// matchRegexString - Can be anything. In this case it checks for if the string is surrounded by braces and grabs with braces.
// endingChar - Can be anything. In this case it checks for if the string is surrounded by braces and grabs w/o braces.
// exampleString - The example string that's passed to the parser
// charName - The character's name. Ideally, this will be dynamic
const matchRegexString = "/\`([^`]*)`/g";
const exampleString = "`She looks very pretty today` Hey! how are you doing? `This is a pen`";
const replaceString = "`{{char}}'s thoughts: {{match}}`"
const charName = "Manami";
// From: https://github.com/IonicaBizau/regex-parser.js/blob/master/lib/index.js
function regexFromString(input) {
// Parse input
var m = input.match(/(\/?)(.+)\1([a-z]*)/i);
// Invalid flags
if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
return RegExp(input);
}
// Create the regular expression
return new RegExp(m[2], m[3]);
}
function parseString(matchRegexString, replaceString, exampleString) {
const matchRegex = regexFromString(matchRegexString);
let newString = exampleString;
while ((match = matchRegex.exec(exampleString)) !== null) {
const fencedMatch = match[0];
const capturedMatch = match[1];
// TODO: Use substrings for replacement. But not necessary at this time.
// A substring is from match.index to match.index + match[0].length or fencedMatch.length
const subReplaceString = substituteParams(replaceString, { regexMatch: capturedMatch, charName });
newString = newString.replace(fencedMatch, subReplaceString);
if (!matchRegex.flags.includes('g')) {
break;
}
}
console.log(newString);
}
// Substitutes parameters
function substituteParams(rawString, { regexMatch, charName }) {
return rawString.replace("{{match}}", regexMatch).replace("{{char}}", charName);
}
parseString(matchRegexString, replaceString, exampleString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment