如何通过正则表达式定位{}内最后逗号分隔后的子串并捕获其中的下划线?
Got it, let's break down how to solve this problem so you can precisely target and replace those underscores.
Your current regex matches everything inside {}, but we need to narrow it down to only underscores that live in the last comma-separated segment of each {...} block. Here's a step-by-step solution:
The Target Regex
Use this regex to match exactly the underscores you need:
_(?=[^},]*})(?<=\{.*,)
How It Works
Let's break down each part to understand why this works:
_: The literal underscore we want to match.(?=[^},]*}): A positive lookahead that ensures, from the underscore to the closing}, there are no commas. This guarantees we're in the last segment of the{...}block.(?<=\{.*,): A positive lookbehind that ensures the underscore is inside a{...}block (we see an opening{before it) and that there's at least one comma before the underscore (so we skip underscores in earlier segments).
Example Usage with regexp_replace
Let's apply this to your sample string. For example, in PostgreSQL (adjust syntax slightly for other languages/environments):
SELECT regexp_replace( '{some_text_1,some_text_1_more,some_text_1_more_more,0_1_2}INTERSECT{some_text_2,some_text_2_more,some_text_2_more_more,text,abc_efg_hijk}', '_(?=[^},]*})(?<=\{.*,)', '-', -- Replace with your preferred delimiter here 'g' -- Global flag to replace all matching underscores );
Result
After replacement, your string will become:
{some_text_1,some_text_1_more,some_text_1_more_more,0-1-2}INTERSECT{some_text_2,some_text_2_more,some_text_2_more_more,text,abc-efg-hijk}
Handling Edge Cases
If you need to handle {...} blocks that have no commas (i.e., the entire block is a single segment where you want to replace all underscores), adjust the regex to:
_(?=[^},]*})(?<=\{[^}]*)
This removes the requirement for a preceding comma, so underscores in single-segment blocks will also be matched.
内容的提问来源于stack exchange,提问作者Itay

