regex_replace由于某种原因只替换了一个出现的情况

huangapple go评论54阅读模式
英文:

regex_replace replaces only one occurrence for some reason

问题

使用正则表达式,我执行了以下操作:

#include <iostream>
#include <regex>
using namespace std;
int main()
{
    string parsed = regex_replace(
        "import core\nimport io\n",
        (regex) "(^|\\r|\\n|\\r\\n)(\\s*)import\\s(.*)\\n",
        "#include \\"$3.h++\\"\\n");
    cout << parsed << endl;
    return 0;
}

我预期的输出应该是:

#include "core.h++"
#include "io.h++"

但实际输出是:

#include "core.h++"
import io

你出现问题的地方在于你的正则表达式没有匹配到第二个 "import" 语句。这是因为你的正则表达式只匹配了一个换行符后的 "import" 语句,而第二个 "import" 语句前面没有换行符,所以没有被匹配到。

要解决这个问题,你可以使用以下正则表达式:

(regex) "(\\s*)import\\s(.*)($|\\n)"

这个正则表达式会匹配所有的 "import" 语句,无论它们是否在行的开头或末尾,并且无论它们是否跟随换行符。这样,你就可以正确替换所有的 "import" 语句了。希望这可以帮助你解决问题。

英文:

With regex, I perform

#include <iostream>
#include <regex>
using namespace std;
int main()
{
    string parsed = regex_replace(
        "import core\nimport io\n",
        (regex) "(^|\r|\n|\r\n)(\\s*)import\\s(.*)\n",
        "#include \"$3.h++\"\n");
    cout << parsed << endl;
    return 0;
}

I expected the output to be:

#include "core.h++"
#include "io.h++"

but it actually was:

#include "core.h++"
import io

Where did I go wrong? Why does it only replace one occurance? Is my regex bad?

I've tried changing the match_flag_options from regex_constants, but to no avail

答案1

得分: 2

你的正则表达式有些过于复杂,可以简化为:

regex(R"(^\s*import\s+([^\s]+)\s*$)", std::regex_constants::multiline)

请注意,我们需要将 std::regex_constants::multiline 作为构造函数参数传递,以便 ^/$ 匹配行的开头/结尾,而不是整个输入的开头/结尾。

(我对你的正则表达式进行了一些更改:

  • 匹配 import 和后面单词之间的多个空格
  • 允许 import 词后的空格(但不允许在该词内部有空格)
  • 不需要匹配行尾字符(在替换中也不需要包括它们!)
  • 使用 原始字符串字面值 语法,因此我们不需要对所有内容进行双重转义。)
英文:

Your regex is somewhat needlessly complicated, it could just be

regex(R"(^\s*import\s+([^\s]+)\s*$)", std::regex_constants::multiline)

Note that we need to pass in std::regex_constants::multiline as a constructor parameter so that ^/$ match the start/end of lines rather than the start/end of the entire input.

(Some changes I've made to your regex:

  • match multiple spaces between import and the word after
  • allow spaces after the 'import' word (and disallow them within that word)
  • no need to match end of line characters (no need to include them in the substitution either!)
  • Use the raw string literal syntax so we don't need to double escape everything
    )

huangapple
  • 本文由 发表于 2023年7月31日 23:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定