Mac端TextWrangler正则处理:两类字符串截取与删除需求
Got it, let's tackle these two questions one by one with clear, step-by-step solutions tailored for TextWrangler:
TextWrangler uses grep-style regex for find-and-replace, so here's how to handle both scenarios:
Scenario 1: Keep only the first two comma-separated fields (remove everything after the second comma)
- Open your target file in TextWrangler, press
Cmd + Fto launch the Find/Replace window. - Check the Grep box in the top-right corner to enable regex mode.
- In the "Find" field, paste this regex:
^([^,]*,[^,]*),.* - In the "Replace" field, enter:
\1 - Click "Replace All" (or use "Replace" first to test individual lines and make sure it works as expected).
How it works:
^anchors the match to the start of the line.([^,]*,[^,]*)captures the first two fields (everything up to and including the content right before the second comma).,.*matches the second comma and all text after it. Replacing with\1keeps only the captured first two fields.
Scenario 2: Remove text after the last comma in each line
- Follow steps 1-2 above to enable Grep mode.
- "Find" regex:
(.*),[^,]*$ - "Replace" with:
\1 - Run replace all or test individual lines as needed.
How it works:
(.*),captures all text up to (and including) the last comma in the line.[^,]*$matches any non-comma characters from the last comma to the end of the line. Replacing with\1strips that trailing part entirely.
Since you mentioned attaching original and expected results, let's use a common example to demonstrate. Suppose your original string looks like this:
"apple","banana","cherry","date","elderberry","fig","grape"
And you want the result to be:
"apple","banana","date","elderberry","grape"
Here's how to do this in TextWrangler (again using Grep mode):
- Open Find/Replace, enable Grep.
- "Find" regex:
((?:[^"]*"[^"]*",){2})[^"]*"[^"]*",((?:[^"]*"[^"]*",){2})[^"]*"[^"]*",(.*) - "Replace" with:
\1\2\3 - Run the replace operation.
How it works:
(?:[^"]*"[^"]*",)is a non-capturing group that matches one full quoted string plus its trailing comma.{2}repeats that group twice to capture the first two quoted strings ("apple","banana",).[^"]*"[^"]*",skips the 3rd quoted string (we don't capture this part, so it gets dropped).- The next
((?:...) {2})captures the 4th and 5th strings ("date","elderberry",). - Another
[^"]*"[^"]*",skips the 6th string. (.*)captures everything after the 6th string (the 7th string here).- Replacing with
\1\2\3stitches together the captured parts, leaving out the 3rd and 6th strings entirely.
If your actual string has a different structure (like no trailing comma, or more/less total strings), just adjust the regex group counts accordingly—this pattern scales as long as you need to skip the 3rd and 6th quoted entries.
内容的提问来源于stack exchange,提问作者joe4java

