如何修改正则表达式,精准匹配含Supply类词汇的特定HTML属性?
Hey there! Let's sort out that regex issue you're facing with targeting those attribute values containing Supply-related terms. Your original regex was too broad and missed some edge cases—here's how to refine it for precise matches:
The Problem With Your Original Regex
Your initial pattern had a few gaps:
- It didn’t restrict matches to the inside of double-quoted attribute values, leading to false positives on unrelated text.
- The
Supply\Ssitesegment incorrectly targeted non-space characters instead of the optional space in "Supply site". - It lacked clear boundaries for attribute names and their values, making it prone to over-matching.
Fixed Regex for Targeting Attributes
Use this pattern in your Ctrl+Shift+F search (make sure "Use Regular Expressions" is enabled):
(Text|HeaderText|ToolTip)="([^"]*(?:Supply\s?site|Suppliers|Supply|Supplier)[^"]*)"
Breakdown of the Pattern:
(Text|HeaderText|ToolTip): Explicitly matches only the attribute names you care about.=": Anchors to the start of the attribute’s double-quoted value.[^"]*: Matches any characters except double quotes (so we stay inside the attribute value).(?:Supply\s?site|Suppliers|Supply|Supplier): A non-capturing group that covers all your target terms—\s?handles the optional space in "Supply site".[^"]*: Continues matching until the closing double quote.": Anchors to the end of the attribute value.
Bonus: Case Insensitivity (If Needed)
If you need to match variations like "supply Site" or "SUPPLIER", add the case-insensitive flag at the start:
(?i)(Text|HeaderText|ToolTip)="([^"]*(?:Supply\s?site|Suppliers|Supply|Supplier)[^"]*)"
How to Replace the Terms
Once you’ve found all matching attributes, you can replace the target terms in two simple steps:
- Use the regex above to locate all relevant attributes.
- For each matched attribute value, run a secondary search-and-replace with this pattern:
- Find:
(Supply\s?site|Suppliers|Supply|Supplier) - Replace:
depot
- Find:
This ensures you only swap the exact terms you want, without touching unrelated text or attributes.
Notes to Keep in Mind
- This regex won’t touch CDATA sections (as requested) since it only targets double-quoted attribute values in your ASPX/ASCX files.
- For your .cs backend files, you’ll need a simpler regex (like
(Supply\s?site|Suppliers|Supply|Supplier)) since you’re targeting string literals rather than HTML attributes.
内容的提问来源于stack exchange,提问作者Eon

