c++ - 将 tag1 tag2 tag3 替换为 x1 x2 x3

标签 c++ regex

我是正则表达式和 C++ 的新手,所以请放轻松 :) !


给定一个像这样的字符串:

输入:

string s = "<ph0/>Hello StackOverflow! Thank you for helping! <ph1/>"

我想分别替换 __ent_00000_ 和 __ent_00001_ 的 ph1 和 ph2 标签,所以最后我希望我的输出是: 输出:

string s = "__ent_00000_Hello StackOverflow! Thank you for helping! __ent_00001_"



我也想做相反的事情,即:

输入:

string s = "__ent_00000_Bye bye StackOverflow!  __ent_00001_"

输出:

string s = "<ph0/>Bye bye StackOverflow!  <ph1/>"


这适用于字符串中任意数量的标签!所以这里的想法是简单地替换但保持数字不变!

我的想法是 regex_replace ( documentation ) 但是 也许还有另一种方法,我愿意接受任何其他可行的解决方案!


带有多个标签的示例:

输入:

string input = "Restaurant is closed<ph0/> <ph1/> <ph2/> <ph3/> | <ph4/> <ph5/>alert<ph6/>We are not serving meals<ph7/> <ph8/> <ph9/> <ph10/> | <ph11/> <ph12/>sorry!"

输出:

string output = "Restaurant is closed__ent_00000_ __ent_00001_ __ent_00002_ __ent_00003_ | __ent_00004_ __ent_00005_alert__ent_00006_We are not serving meals__ent_00007_ __ent_00008_ __ent_00009_ __ent_00010_ | __ent_00011_ __ent_00012_sorry!"

谢谢你,祝你有美好的一天! :)

最佳答案

如果您对这个问题的第一个解决方案涉及正则表达式,那么您就注定要失败。 请不要!(一个简单的字符串替换就足够了)。

如果每个标签只出现一次,您真正需要做的就是调用 string::replace在他们。即使它们出现多次,使用 boost 的 replace_all()算法。

关于c++ - 将 tag1 tag2 tag3 替换为 x1 x2 x3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61035172/

相关文章:

regex - Dart 正则表达式 : Only allow dot and numbers

c++ - 要不要使用事件对象?

c# - c++ dll结构到c#

c++ - cpp : delete folder open by others

c++ - 我如何将 .h 文件中的代码实现到 main.cpp 文件中?

c# - 在 HttpContext.Cache 中搜索时使用通配符

sql - 如何在 where 子句中使用正则表达式来过滤 Postgres 中的行?

c++如何让用户输入方程式进行评估

javascript - 使用 native 除法运算符对解码的 URI 十六进制代码使用 Replace()

c# 正则表达式在一些 html 标签中