Skip to content

Instantly share code, notes, and snippets.

@hymerman
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save hymerman/8e1f500bb5787092a6d0 to your computer and use it in GitHub Desktop.

Select an option

Save hymerman/8e1f500bb5787092a6d0 to your computer and use it in GitHub Desktop.
Visual Studio Find and Replace Regular Expressions to replace c# 'foreach' loops with 'for' loops
Visual Studio Find and Replace Regular Expressions to replace c# 'foreach' loops with 'for' loops.
Useful for Unity scripts that want to reduce dynamic allocations.
Container is assumed to be List, so 'Count' is used rather than Length - will need fixing up after replacement if this is wrong.
Replacements follow this pattern:
foreach (Type name in container)
{
... becomes:
for (int nameIndex = 0; nameIndex < container.Count; ++nameIndex)
{
Type name = container[nameIndex];
Also supports type containing "." and ending in "[]", and container containing ".".
Settings to use in Find and Replace dialogue:
Find what:
(?<whitespace>[^\S\r\n]+)foreach[ \t]*\([ \t]*\b(?<type>_+\w+|[\w-[0-9_]][\w\.]*[ \t]*(\[[ \t]*\])?)[ \t]+\b(?<name>_+\w+|[\w-[0-9_]][\w\.]*)\b[ \t]+in[ \t]+\b(?<container>_+\w+|[\w-[0-9_]][\w\.]*)\b[ \t]*\)[ \t\r\n]*{
Replace with:
${whitespace}for (int ${name}Index = 0; ${name}Index < ${container}.Count; ++${name}Index)\r\n${whitespace}{\r\n${whitespace} ${type} ${name} = ${container}[${name}Index];
Find options:
[ ] Match case
[ ] Match whole word
[x] Use Regular Expressions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment