diff --git a/src/utils.cpp b/src/utils.cpp index 6f22234248..5caac6e23f 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -108,6 +108,21 @@ bool utils::strmatch(const std::string &text, const std::string &pattern) return (pos >= 0); } +/** This function is a companion function to utils::strmatch(). Arguments + * and logic is the same, but instead of a boolean, it returns the + * substring that matches the regex pattern. There can be only one match. + * This can be used as a more flexible alternative to strstr(). + */ +std::string utils::strfind(const std::string &text, const std::string &pattern) +{ + int matchlen; + const int pos = re_find(text.c_str(),pattern.c_str(),&matchlen); + if ((pos >=0) && (matchlen > 0)) + return text.substr(pos,matchlen); + else + return ""; +} + /** This function simplifies the repetitive task of outputting some * message to both the screen and/or the log file. In combination * with using fmt::format(), which returns the formatted text diff --git a/src/utils.h b/src/utils.h index eece00f306..8da7a40e25 100644 --- a/src/utils.h +++ b/src/utils.h @@ -37,6 +37,14 @@ namespace LAMMPS_NS { bool strmatch(const std::string &text, const std::string &pattern); + /** Find substring that matches a simplified regex pattern + * + * \param text the text to be matched against the pattern + * \param pattern the search pattern, which may contain regexp markers + * \return the string that matches the patters or an empty one */ + + std::string strfind(const std::string &text, const std::string &pattern); + /** Send message to screen and logfile, if available * * \param lmp pointer to LAMMPS class instance