简体   繁体   English

正则表达式用另一个字符替换 C++ 中的单个字符

[英]Regex to replace single occurrence of character in C++ with another character

I am trying to replace a single occurrence of a character '1' in a String with a different character.我试图用不同的字符替换字符串中出现的单个字符“1”。

This same character can occur multiple times in the String which I am not interested in.这个相同的字符可以在我不感兴趣的字符串中出现多次。

For example, in the below string I want to replace the single occurrence of 1 with 2.例如,在下面的字符串中,我想用 2 替换单个出现的 1。

 input:-0001011101

 output:-0002011102

I tried the below regex but it is giving be wrong results我尝试了下面的正则表达式,但它给出了错误的结果

  regex b1("(1){1}"); 
  S1=regex_replace( S,
              b1,  "2");

Any help would be greatly appreciated.任何帮助将不胜感激。

If you used boost::regex , Boost regex library, you could simply use a lookaround-based solution like如果您使用boost::regex ,Boost regex 库,则可以简单地使用基于环视的解决方案,例如

(?<!1)1(?!1)

And then replace with 2 .然后用2替换。

With std::regex , you cannot use lookbehinds, but you can use a regex that captures either start of string or any one char other than your char, then matches your char, and then makes sure your char does not occur immediately on the right.使用std::regex ,您不能使用lookbehinds,但您可以使用一个正则表达式来捕获字符串的开头或除您的字符之外的任何一个字符,然后匹配您的字符,然后确保您的字符不会立即出现在右侧.

Then, you may replace with $01 backreference to Group 1 (the 0 is necessary since the $12 replacement pattern would be parsed as Group 12, an empty string here since there is no Group 12 in the match structure):然后,您可以将$01反向引用替换为 Group 1( 0是必需的,因为$12替换模式将被解析为 Group 12,此处为空字符串,因为匹配结构中没有 Group 12):

regex reg("([^1]|^)1(?!1)"); 
S1=std::regex_replace(S, regex, "$012");

See the C++ demo online :在线查看C++ 演示

#include <iostream>
#include <regex>

int main() {
    std::string S = "-0001011101";
    std::regex reg("([^1]|^)1(?!1)");
    std::cout << std::regex_replace(S, reg, "$012") << std::endl;
    return 0;
}
// => -0002011102

Details :详情

  • ([^1]|^) - Capturing group 1: any char other than 1 ( [^...] is a negated character class) or start of string ( ^ is a start of string anchor) ([^1]|^) - 捕获组 1:除1以外的任何字符( [^...]是否定字符类)或字符串的开头( ^是字符串锚的开头)
  • 1 - a 1 char 1 - 1字符
  • (?!1) - a negative lookahead that fails the match if there is a 1 char immediately to the right of the current location. (?!1) - 如果当前位置右侧有1字符,则匹配失败的负前瞻。

The flag std::regex_constants::format_first_only tells regex_replace() to replace just the first match instead of all matches.标志std::regex_constants::format_first_only告诉regex_replace()只替换第一个匹配项而不是所有匹配项。

The {1} quantifier doesn't do this, it just controls how many characters are in each match, not how many replacements are done. {1}量词不这样做,它只是控制每个匹配中有多少字符,而不是完成多少替换。 All patterns match one time unless quantified otherwise, so {1} is always redundant.除非以其他方式量化,否则所有模式都匹配一次,因此{1}始终是多余的。

S1 = regex_replace(S, b1, "2", std::regex_constants::format_first_only)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM