使用正则表达式在C++中从字符串中提取数字。

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

extract digits from string using Regex in c++

问题

我已经创建了这个C++代码来从由xxx和yyy限制的混合字符串中提取数字。以下是我的代码:

#include <iostream>
#include <regex>

using namespace std;

int main() {

    string text = "xxx1111yyy xxxrandomstring2222yyy";

    string start_delimiter = "xxx";

    string end_delimiter = "yyy";

    regex pattern(start_delimiter + "([0-9]+)" + end_delimiter);

    smatch match;

    while (regex_search(text, match, pattern)) {

        cout << match[1] << endl;

        text = match.suffix().str();

    }

    return 0;
}

我期望的输出是:

1111
2222

但我只得到输出:1111
我的问题在哪里?

英文:

I have created this c++ to extract digits from mixed strings limited by xxx and yyy
Here is my code

#include &lt;iostream&gt;

#include &lt;regex&gt;

using namespace std;

int main() {

    string text = &quot;xxx1111yyy xxxrandomstring2222yyy&quot;;

    string start_delimiter = &quot;xxx&quot;;

    string end_delimiter = &quot;yyy&quot;;

    regex pattern(start_delimiter + &quot;([0-9]+)&quot; + end_delimiter);

    smatch match;

    while (regex_search(text, match, pattern)) {

        cout &lt;&lt; match[1] &lt;&lt; endl;

        text = match.suffix().str();

    }

    return 0;

}

I expect the output:

1111
2222

But I'm getting in output only: 1111
Where is my fault ?

答案1

得分: 0

如我所理解,分隔符 xxxyyyy 是静态的,randomstring 不是静态的,所以它可以是任何随机字符串。所以错误实际上在于你的正则表达式模式。它应该类似于这样:

regex pattern("xxx.*?(\\d+).*?yyy");

整个代码可以像这样:

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string text = "xxxrandomstring2222yyy xxx1111yyy";
    std::regex pattern("xxx.*?(\\d+).*?yyy");
    std::smatch match;

    while (std::regex_search(text, match, pattern)) {
        std::cout << match[1] << std::endl;
        text = match.suffix().str();
    }

    return 0;
}
英文:

As I understand, delimiters xxx and yyyy are statics, randomstring isn't static so it can be any random string.
So the error simply is in your regex pattern.
it should something like this:

regex pattern(&quot;xxx.*?(\\d+).*?yyy&quot;);

The whole code could be like this:

#include &lt;iostream&gt;
#include &lt;regex&gt;
#include &lt;string&gt;

int main() {
std::string text = 
&quot;xxxrandomstring2222yyy xxx1111yyy&quot;;
std::regex pattern(&quot;xxx.*?(\\d+).*?yyy&quot;);
std::smatch match;


while (regex_search(text, match, pattern)) {

    std::cout &lt;&lt; match[1] &lt;&lt; std::endl;

    text = match.suffix().str();

}

return 0;
}

huangapple
  • 本文由 发表于 2023年2月6日 08:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356373.html
匿名

发表评论

匿名网友

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

确定