我有一个看起来像这样的字符串
text here++ text
+ text text
+ text
text text
Run Code Online (Sandbox Code Playgroud)
我想将 + 替换为 - 但仅在行的开头,这样它看起来像这样:
text here++ text
- text text
- text
text text
Run Code Online (Sandbox Code Playgroud)
我正在尝试这样的正则表达式:
string text = "the-above-text";
regex reg("^\\++.*$");
text = regex_replace(text, reg, "-");
Run Code Online (Sandbox Code Playgroud)
但是这个 ^ 匹配文本的开头,而不是行的开头。
我已经搜索了几个小时,似乎没有办法让引擎在多行模式下工作。
我有办法做到这一点吗?或者任何支持多行 ^ 和 $ 的较新的 C++ 标准?我正在使用 g++
谢谢!
要匹配行尾或字符串开头,请使用(^|\n)交替组。
+要将每行开头的1 个以上字符替换为单个-(连字符),请使用
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::string s = "text here++ text\n+ text text\n+ text\ntext text";
std::regex r("(^|\n)\\++");
std::cout << std::regex_replace(s, r, "$1-") << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请参阅C++ 演示。
请注意,要将换行符重新插入到结果中,$1引用组 1 值的占位符将在替换模式中使用(否则,它将被删除)。