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

正则表达式匹配文本键值对:解决值过度匹配及指定键匹配需求

Solution for Matching Valid Key-Value Pairs with Regex

The issue with your original regex is that the greedy .* quantifier is matching all characters from the first valid value all the way to the end of the file, instead of stopping at the closing quote of the current value. Here's a corrected regex that fixes this and only matches pairs where the value contains at least one lowercase letter or digit:

"([A-Z]+)"\s*"([^"]*[a-z\d][^"]*)"

Breakdown of the Regex:

  • "([A-Z]+)": Matches the key (uppercase letters enclosed in double quotes) and captures the key into group 1.
  • \s*: Optional whitespace between the key's closing quote and the value's opening quote (handles cases where there might be spaces or tabs).
  • "([^"]*[a-z\d][^"]*)": Matches the value enclosed in double quotes, with the following rules:
    • [^"]*: Matches any number of characters except double quotes (prevents the regex from spilling into the next key-value pair).
    • [a-z\d]: Ensures the value contains at least one lowercase letter or digit (the required condition for a valid value).
    • The surrounding [^"]* allows any other characters (including uppercase letters, symbols, etc.) before and after the required lowercase/digit.

How It Works with Your Example:

For the input text: "ADDRESS""32 street 90. ETC""AGE""13""CLASS""ABC"

  • It will match "ADDRESS""32 street 90. ETC" (value has digits and lowercase letters)
  • It will match "AGE""13" (value has a digit)
  • It will not match "CLASS""ABC" (value has no lowercase letters or digits)

Usage Notes:

  • If you're using this in a regex engine that supports global matching (like JavaScript's g flag, or Python's re.findall), it will return all valid key-value pairs in the text.
  • If you need to capture just the key and value (without the quotes), the captured groups 1 and 2 will give you those values directly.

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:42:27