74 lines
1.4 KiB
C++
74 lines
1.4 KiB
C++
#ifndef DLANG_LIBS_REGEX_HPP
|
|
#define DLANG_LIBS_REGEX_HPP
|
|
|
|
#include <regex>
|
|
#include <string>
|
|
#include "../vm.hpp"
|
|
#include "../helpers.hpp"
|
|
|
|
static void NativeRegexMatch(DlangVM* vm)
|
|
{
|
|
auto pattern = dlang_tostring(vm);
|
|
auto text = dlang_tostring(vm);
|
|
|
|
try {
|
|
std::regex rx(pattern);
|
|
bool matched = std::regex_match(text, rx);
|
|
dlang_pushboolean(vm, matched);
|
|
}
|
|
catch (...) {
|
|
dlang_pushboolean(vm, false);
|
|
}
|
|
}
|
|
|
|
static void NativeRegexSearch(DlangVM* vm)
|
|
{
|
|
auto pattern = dlang_tostring(vm);
|
|
auto text = dlang_tostring(vm);
|
|
|
|
try {
|
|
std::regex rx(pattern);
|
|
bool found = std::regex_search(text, rx);
|
|
dlang_pushboolean(vm, found);
|
|
}
|
|
catch (...) {
|
|
dlang_pushboolean(vm, false);
|
|
}
|
|
}
|
|
|
|
static void NativeRegexReplace(DlangVM* vm)
|
|
{
|
|
auto fmt = dlang_tostring(vm);
|
|
auto pattern = dlang_tostring(vm);
|
|
auto text = dlang_tostring(vm);
|
|
|
|
try {
|
|
std::regex rx(pattern);
|
|
std::string result = std::regex_replace(text, rx, fmt);
|
|
|
|
dlang_pushstring(vm, result);
|
|
dlang_pushindex(vm);
|
|
}
|
|
catch (...) {
|
|
dlang_pushstring(vm, text);
|
|
dlang_pushindex(vm);
|
|
}
|
|
}
|
|
|
|
inline void openlib_regex(DlangVM* vm)
|
|
{
|
|
dlang_newtable(vm);
|
|
|
|
dlang_pushcfunction(vm, NativeRegexMatch);
|
|
dlang_setfield(vm, "match");
|
|
|
|
dlang_pushcfunction(vm, NativeRegexSearch);
|
|
dlang_setfield(vm, "search");
|
|
|
|
dlang_pushcfunction(vm, NativeRegexReplace);
|
|
dlang_setfield(vm, "replace");
|
|
|
|
dlang_setglobal(vm, "regex");
|
|
}
|
|
|
|
#endif |