Skip to content

Instantly share code, notes, and snippets.

@bdashore3
Last active July 2, 2023 03:58
Show Gist options
  • Save bdashore3/6e09bccc85c640a688e07e8a9481d62c to your computer and use it in GitHub Desktop.
Save bdashore3/6e09bccc85c640a688e07e8a9481d62c to your computer and use it in GitHub Desktop.
SillyTavern POC easy regex engine. No regex knowledge required!
// Goal: Provide regex beginning/end replacement without the need for users to know regex
// Advantages:
// - Allows for checks if the character is the same (ex. backticks)
// - Simplified UI for users (just need a start character, end character, and replacement string)
// Disadvantages:
// - Lack of inputting a raw regex string
// - Less flexibility, covers less usecases
// beginningChar - The beginning char(s) to look for
// endingChar - The ending char(s) to look for
// exampleString - The example string that's passed to the parser
// replaceString - A string-variable string that can include the regex match. Used with replaceRegex
// charName - The character's name. Ideally, this will be dynamic
const beginningChar = "{";
const endingChar = "}";
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";
// Creates regexp and parses a provided string + replaces it with what's needed
function parseString(beginningChar, endingChar, replaceString, exampleString) {
// Contains a lookahead and lookbehind to ignore the beginning/ending chars in matches
const matchRegex = new RegExp(`(?<=${beginningChar})[^${endingChar}]*(?=${endingChar})`, "g");
// Want the beginning/ending chars in these matches
const replaceRegex = new RegExp(`(${beginningChar}[^${endingChar}]*${endingChar})`, "g");
const matched = exampleString.match(matchRegex);
let newString = exampleString;
matched.forEach((regexMatch, index) => {
const subReplaceString = substituteParams(replaceString, { regexMatch, charName });
// Get all matches including their symbols by globally running the replaceRegex
let replaceMatches = exampleString.match(replaceRegex);
// Look for the specific index for replace searching and swap in the new stuff
newString = newString.replace(replaceMatches[index], subReplaceString);
});
console.log(newString);
}
// Substitutes parameters
function substituteParams(rawString, { regexMatch, charName }) {
return rawString.replace("{{match}}", regexMatch).replace("{{char}}", charName);
}
parseString(beginningChar, endingChar, replaceString, exampleString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment