英文:
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 <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;
}
I expect the output:
1111
2222
But I'm getting in output only: 1111
Where is my fault ?
答案1
得分: 0
如我所理解,分隔符 xxx 和 yyyy 是静态的,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("xxx.*?(\\d+).*?yyy");
The whole code could be like this:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text =
"xxxrandomstring2222yyy xxx1111yyy";
std::regex pattern("xxx.*?(\\d+).*?yyy");
std::smatch match;
while (regex_search(text, match, pattern)) {
std::cout << match[1] << std::endl;
text = match.suffix().str();
}
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论