【问题标题】:Regex matching to change ES module import to direct import正则表达式匹配将 ES 模块导入更改为直接导入
【发布时间】:2020-10-21 18:14:12
【问题描述】:

我有一个组件库包,它被用于很多这样的文件中:

import { Grid, Heading, Button } from 'component-library'

我想将我的所有导入更改为这样的:

import { Grid } from 'component-library/lib/Grid'
import { Heading } from 'component-library/lib/Heading'
import { Button } from 'component-library/lib/Button'

我在 VSCode 上找到了一个用于执行此操作的扩展:
https://marketplace.visualstudio.com/items?itemName=angelomollame.batch-replacer&ssr=false#overview

而且它似乎也接受正则表达式。 我试图编写一个正则表达式来查找将旧导入替换为新的,但我的正则表达式不起作用。这是我当前的正则表达式:

(?:import)\s+([\w,{}\s\*]+)\s+(?:from)?\s*(?:["'])?([@\w\s\\\/.-]+)(?:["'])?\s*

你能帮我解决这个问题吗?

【问题讨论】:

标签: javascript regex visual-studio-code regex-group regexp-replace


【解决方案1】:

您可以分两步完成(这和我的 regex-fu 一样好)。

第 1 步:

(import \{ )?((\w+)[, ]+)(?=.*?(\} from '(.*)')) 搜索正则表达式

import { $3 } from '$5/lib/$3'\n查找正则表达式

Regex101


这会为每个原始 import 行留下一个杂散的 } from 'great-library'; (也许有人可以改进正则表达式来避免这种情况),所以删除它:

^\} from.*$搜索

什么都没有。


有一些多正则表达式替换扩展,您可以将这两个步骤合二为一。例如,使用Batch Replacer 试试这个“脚本”:

replace-regex "(import { )?((\w+)[, ]+)(?=.*?(} from '(.*)'))"
with "import { $3 } from '$5/lib/$3'\n"

replace-regex "(?<!.)} from.*\r?\n?"
with ""

【讨论】:

    【解决方案2】:

    没有任何扩展,只要有匹配就使用正则表达式:

    查找:

    (import\s*{\s*)(\w+)\s*,([\w\s,*]+?)(\s*}(?:\s*from)?\s*)(["'])?([@\w\s\\/.-]*?)\5
    

    替换:

    $1$2$4$5$6$5\n$1$3$4$5$6$5
    

    见regex demo

    模式将匹配并捕获部分模式到单独的组中。每次只会捕获圆括号中的第一个单词,并输出仅包含该单词的行 + 换行符和包含括号内其他单词的行。

    这就是为什么您需要运行搜索和替换直到找不到匹配项。

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2016-07-11
      相关资源
      最近更新 更多