Python re.sub替换双引号内分号时误替换整段内容的问题
Got it, let's sort out this regex problem you're facing. The issue with your current code is that it's matching the entire quoted substring containing a semicolon and replacing the whole thing with a comma—instead of just swapping out the semicolons inside the quotes. Here's how to fix it properly:
The Right Approach: Use a Callback Function
Instead of replacing the entire quoted block, we can use a callback function with re.sub to target only the semicolons inside the matched quoted text. Here's the breakdown:
- First, write a regex that matches entire double-quoted strings (not just fragments of them).
- Pass a function to
re.subthat takes each matched quoted string, replaces semicolons with commas inside it, and returns the modified string.
Corrected Code
import re a = '19905;"CANDIES,CHOC,DK,NFS (45-59% CACAO SOL 90%; 60-69% CACAO SOL";1;550;5,09;32,2;1,74;59,97;7,2;46,14;57;8,13;152;214;568;23;2,11;1,076;1,44;3,5;0;0,026;0,051;0,747;0,304;0,041;0;0;0;0;27,6;0,23;49;2;0;7;25;1;0;31;0,55;0;0;8;18,993;9,801;1,107;7;28,35;1 oz;127;1 bar;0' def swap_semicolons_in_quotes(match): # Grab the full quoted string (including the quotes) quoted_content = match.group(0) # Replace only the semicolons inside this string return quoted_content.replace(';', ',') # Run the substitution fixed_string = re.sub(r'"[^"]+"', swap_semicolons_in_quotes, a) print(fixed_string)
Simplified Version with Lambda
If you prefer a more concise one-liner, use a lambda function instead of a named function:
fixed_string = re.sub(r'"[^"]+"', lambda m: m.group(0).replace(';', ','), a)
What This Does
- The regex
r'"[^"]+"'correctly matches every double-quoted substring (from the opening"to the closing"). - For each match, we only modify the content inside the quotes by swapping
;to,, leaving the quotes and all other parts of the original string untouched.
Result
Your quoted substring will change from:
"CANDIES,CHOC,DK,NFS (45-59% CACAO SOL 90%; 60-69% CACAO SOL"
To:
"CANDIES,CHOC,DK,NFS (45-59% CACAO SOL 90%, 60-69% CACAO SOL"
All semicolons outside the quotes (like the ones separating your CSV fields) will stay exactly as they are.
内容的提问来源于stack exchange,提问作者alexe-mgn

