如何修改正则表达式以提取分号闭合内的数字-字符串对?
Your current regex matches any sequence of digits followed by a comma and non-semicolon/comma characters, which is why it's picking up 135,jkl — that substring fits the pattern and ends at the end of the string, even though it's part of a longer semicolon-separated segment (789,ghi,135,jkl).
To fix this, we need to ensure the "number,String" pair is the entire content of a semicolon-separated segment. We can do this by anchoring the match to the boundaries of these segments (either start/end of the string or a semicolon):
Modified Regex
std::regex regex(R"(?:^|;)(\d+),([^,;]+)(?:;|$)");
Or if you prefer not to use raw string literals:
std::regex regex("(?:^|;)(\\d+),([^,;]+)(?:;|$)");
Breakdown of the Regex Parts:
(?:^|;): Non-capturing group that matches either the start of the string or a semicolon. This ensures our pair starts at the beginning of a semicolon-separated segment.(\d+): Captures one or more digits (your number component).,: Matches the literal comma separator.([^,;]+): Captures one or more characters that are not commas or semicolons. This guarantees the string part has no extra separators, so the segment is exactly one "number,String" pair.(?:;|$): Non-capturing group that matches either a semicolon or the end of the string. This ensures our pair ends at the conclusion of a semicolon-separated segment.
Modified Code
#include <iostream> #include <regex> #include <string> int main() { std::string input_string = ";;abc,123;,,;456,def;789,ghi,135,jkl"; std::regex regex(R"(?:^|;)(\d+),([^,;]+)(?:;|$)"); for (std::sregex_iterator it(input_string.begin(), input_string.end(), regex), itEnd; it != itEnd; ++it) { std::cout << it->str(1) << ", " << it->str(2) << std::endl; } return 0; }
Output
456, def
This will only match the 456,def pair, as it's the only segment that meets your requirement of being a standalone "number,String" pair enclosed within semicolons.
内容的提问来源于stack exchange,提问作者user3724853

