[英]C++ Remove all the spaces before punctuation signs and add spaces if none exist after punctuation signs
C++ problem - I need to : C++ 问题 - 我需要:
I would appreciate an explanation of how it works and any ideas on how I could modify it to cover the second part of the problem as well.我希望能解释一下它是如何工作的,以及我如何修改它以涵盖问题的第二部分的任何想法。 There are no limitations except I'm not looking for any solutions based on hardcoded strings没有任何限制,除非我不是在寻找基于硬编码字符串的任何解决方案
std::string fix_string(const std::string& str) {
static const std::regex rgx_pattern("\\s+(?=[\\.,])");
std::string rtn;
rtn.reserve(str.size());
std::regex_replace(std::back_insert_iterator<std::string>(rtn), str.cbegin(), str.cend(), rgx_pattern, "");
return rtn;
}
Input example : I would ,if at all possible , like to write this sentence properly .输入示例:如果可能的话,我会喜欢正确地写出这句话。
Desired outcome : I would, if at all possible, like to write this sentence properly.期望的结果:如果可能的话,我会喜欢正确地写下这句话。
Your example matches "one or more spaces" that is followed by period or comma (without matching the period or comma), and replaced those spaces with nothing.您的示例匹配后跟句点或逗号(不匹配句点或逗号)的“一个或多个空格”,并将这些空格替换为空。
This modifies is so the regex matches "any number of spaces, dot or comma, any number of spaces", and replaces the entire match with the dot or comma ($1 refers to the part of the pattern in parens) followed by one space.这修改了正则表达式匹配“任意数量的空格,点或逗号,任意数量的空格”,并将整个匹配替换为点或逗号($1 指括号中的模式部分)后跟一个空格。
std::string fix_string(const std::string& str) {
static const std::regex rgx_pattern("\\s*([.,])\\s*");
std::string rtn;
rtn.reserve(str.size());
std::regex_replace(std::back_insert_iterator<std::string>(rtn), str.cbegin(), str.cend(), rgx_pattern, "$1 ");
return rtn;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.