Search code examples
regexvisual-studio-codereplace

How to do this multi-line regex find-and-replace in VSC?


/const meta = ([\s\S]*?) satisfies (Meta(.+));/g with a replace of const meta: $2 = $1; seems to be what I want, according to certain systems (e.g. regex101.com).

But it doesn't work in VSCode.

Example text to search:

const meta = {
  args: {
    description: 'This is a test alert for interaction testing.',
  },
  argTypes: {
    hasBackground: {
      control: 'boolean',
    },
    variant: {
      control: { type: 'select' },
    },
  },
  component: Alert,
  parameters: {
    design: {
      type: 'figma',
    },
  },
  title: 'Component/Alert',
} satisfies Meta<typeof Alert>;


const meta = {
  argTypes: {
    number: {
      if: { arg: 'size', eq: 'lg' },
    },
    size: {
      options: ['sm', 'md', 'lg'],
    },
    variant: {
      control: 'select',
    },
  },
  component: Badge,
  parameters: {
    design: {
      type: 'figma',
    },
  },
  title: 'Component/Badge',
} satisfies Meta<typeof Badge>;

Successful replacement:

enter image description here

How can I accomplish this regex find-and-replace in VSC across all my project's files?

Or is there some other tool I should use?


Solution

  • Regex Multiline searches in VSCode

    VSCode only includes newlines in search when a \n literal is included (see further reading section), so a potential solution here is to add \n to the character set (within [\S\s])

    The 'find' pattern should be updated to:

    /const meta = ([\n\s\S]*?) satisfies (Meta(.+));/g
    

    The replace pattern is fine as suggested in the original question.

    Further reading

    Multiline regular expression search in Visual Studio Code https://code.visualstudio.com/updates/v1_29#_multiline-search