You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改正则表达式以提取分号闭合内的数字-字符串对?

Fixing the Regex to Match Only Semicolon-Enclosed "Number,String" Pairs

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:00:20